2017-08-17 71 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

认为它的工作原理:)。 –