2017-08-17 66 views
1

我已經創建了一個android服務,我希望它繼續運行,直到我要求它從活動中關閉。我已經創建它START_STICKY返回onStartcommand(),工作正常,即使我關閉應用程序保持運行。但問題是我想停止按鈕單擊服務(例如單選按鈕:在後臺運行是/否)。如何從活動中停止START_STICKY android服務

public class MyService extends Service { 
    public MyService() { 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     return START_STICKY; 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 
} 

回答

0

在您的按鈕的onClick()方法,這樣做:

Intent intent = new Intent(MyActivity.this, MyService.class); 
stopService(intent); 
+0

認爲它的工作原理:)。 –