简体   繁体   中英

How to stop a service after it has finished its job?

I have a service which I start from my Activity. Now the serivce performs some task by starting a new thread from onStartCommand() I want to stop the service after the thread has finished its job.

I tried using a Handler like this

  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();
        }
    }

First it was giving me a warning that if handler class is not static it will cause leaks After I made it static, stopSelf() can not be called, because its non static.

Is my approach correct or is there a simpler way around ?

you should use IntentService rather service. It starts automatically in separate thread and stop itself as task completes.

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. 

    }

}

Use IntentService its base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

try this,

private static class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {            
            super.handleMessage(msg);
            Log.e("", "INSIDE handleMEssage");
           MainService.this.stopSelf();;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM