完成服务后如何停止服务?

Ank*_*kit 1 service multithreading android

我有一项从我的活动开始的服务。现在,服务通过从onStartCommand()启动新线程来执行某些任务,我想在线程完成其工作后停止该服务。

我尝试使用这样的处理程序

  public class MainService extends Service{

    private Timer myTimer;
    private MyHandler mHandler;


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mHandler = new MyHandler();
        myTimer = new Timer();
        myTimer.schedule(new MyTask(), 120000);
        return 0;
    }

    private class MyTask extends TimerTask{

        @Override
        public void run() {
            Intent intent = new Intent(MainService.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            mHandler.sendEmptyMessage(0);
        }

    }

    private static class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {            
            super.handleMessage(msg);
            Log.e("", "INSIDE handleMEssage");
            //stopSelf();
        }
    }
Run Code Online (Sandbox Code Playgroud)

首先,它向我发出警告,如果处理程序类不是静态的,则会导致泄漏。在我将其设置为静态之后,由于其非静态,因此无法调用stopSelf()。

我的方法正确还是有更简单的方法?

Bir*_*dia 5

您应该使用IntentService而不是服务。它在单独的线程中自动启动,并在任务完成时自行停止。

public class MyService extends IntentService {

    public MyService(String name) {
        super("");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {

        // write your task here no need to create separate thread. And no need to stop. 

    }

}
Run Code Online (Sandbox Code Playgroud)