简体   繁体   中英

This is the correct way to repeat method every x second in service?

I write a method on service to run every x seconds. But there are some problems.

What I did is

public class noti extends Service  {
      Context mcont; 
      private Handler myhandler ;
      private long RETRY_TIME = 15000; 
      private long START_TIME = 2000; 

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

  @Override
  public void onStart(Intent intent, int startId) { 

  }
  @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     mcont=this;
     myhandler= new Handler();
     myhandler.postDelayed(myRunnable, START_TIME);
     return super.onStartCommand(intent, flags, startId);

    }
    @Override
  public void onDestroy() { 
        super.onDestroy();  
        try {
            myhandler.removeCallbacks(myRunnable); 
        } catch (Exception e) {
            // TODO: handle exception
        }
  }



    private Runnable myRunnable = new Runnable() {
           public void run() { 
           try {
                new get_notifyalert_service(mcont).execute("")  ; 
            } catch (Exception e) {
                // TODO: handle exception
            }  
            myhandler.postDelayed(myRunnable, RETRY_TIME);
           }
        };
}

this is the right way?

on the phone when I check the settings->apps->running-apps it says sometimes restarting and it took long time

thanks in advance

I see two problems in your solution:

First: Your commands will indeed be activated periodically, but they will do so on the main thread . In many cases, maybe most, you want your periodical processing to run on a separate thread.


if that is what you want, a timer will be a better option:


  t = new Timer();
  task = new TimerTask() {
       @Override
       public void run() {
           // do periodical action <-------------
       }
  };
  t.scheduleAtFixedRate(task, 0, 1000);


Second: your service will, sooner or later, be reclaimed by Android, stopping the periodical processing.

For many apps this is not a real problem. You do not really want your background logic running all the time.

If that is not the case for you, declare your service as a foreground service (ie guaranteed not to be killed by Android):


Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);


..Or, at minimum, set it to be sticky:

public class StickyService extends Service {

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

}

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