开发者

Function written in servcie run even the Service got Destroyed

开发者 https://www.devze.com 2023-04-12 16:35 出处:网络
I have written a function in service which is executing when service start .My service class is as follows

I have written a function in service which is executing when service start .My service class is as follows

public class SimpleService extends Service {
     public static final String TAG = "Service";
     private Timer timer = new Timer();
     @Override

     public IBinder onBind(Intent arg0) {
           return null;
     }

     @Override

     public void onCreate() {
           super.onCreate();

           Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();           
           Log.i(getClass().getSimpleName(), "Service started.");         
           startService() ;
     }

     @Override
     public void onDestroy() {
           super.onDestroy();

           Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
     }

     private void startService() {                   
         timer.scheduleAtFixedRate(new mainTask(), 0, 200000);   
 开发者_运维问答    }    

     private class mainTask extends TimerTask {         
         public void run() {           
             for (int i = 0; i <300; i++) { 
                 String count= String.valueOf(i);
                 Log.d(TAG, count);
             }
         } 
     }

     protected Intent  launchmain_menu() {
             Intent i = new Intent(this, SimpleService.class);
             return i;
     }

}

I have started my service in my main activity on create mentod as below startService(new Intent(this, SimpleService.class));

Also I have written on button click to destroy the service as below stopService(launchmain_menu());

protected Intent  launchmain_menu() {
    Intent i = new Intent(this, SimpleService.class);
    return i;
}

The Problem is that even when i destroy the service the loop in the start service function

ie..

for (int i = 0; i <300; i++) { 
                 String count= String.valueOf(i);
                 Log.d(TAG, count);
}

get executed.I have check the running service in the emulitor but the service started my me is not there after i clicked the button to destroy the service.How wil the loop got executed even the service is destroyed.

Will any one help me after review this code pls.


The loop gets executed because it is executed on a different thread, using the Timer you've created. As I can read in the Timer android documentation the Timer tasks cannot be stopped once they have started, so you will have to cancel it before its scheduled time, wait until the task has completed, or do it in a different way.


You need to free all the resources, listeners etc from the service on your own as android does not do it for you.Use onDestroy() method to free all your resources. Refer this doc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号