Using Service, TimerTask and BroadcastReceiver to check for various updates

六眼飞鱼酱① 提交于 2019-12-04 10:34:26
  • You are creating and unregistering a new Receiver instance, but that has no effect on the receiver you have registered in the manifest file. Try removing it from the manifest.
  • You never cancel the Timer that's why it keeps firing. Stopping the service doesn't automatically stop threads you have created (such as the one used by the Timer)

Generally, you should use AlarmManager with an IntentService to schedule repeating background tasks. A Timer is unreliable and doesn't fit too well with the Android framework. Also, a Timer won't execute if the phone is asleep. You can have alarms wake up the phone to execute (whether that is a good idea for a news-updating service is another matter) with AlarmManager.

EDIT

This in combination with Nikolay Elenkov suggestion about using ScheduledThreadPoolExecutor provided a very nice solution.


I found a solution that fits my purpose better than using a Service and BroadcastReceiver. I have no need to check for news/updates when the app is not running, so using a service would be overkill and just use more data than needed. I found that using Handlers was the way to go. Here is the implementation that works perfectly:

Avtivity:

public class UpdateServiceActivity extends Activity implements OnClickListener {
   private Handler handlerTimer;
   private Runnable newsHandler;

   @Override
   public void onCreate( Bundle savedInstanceState ) {
      handlerTimer = new Handler();
      newsHandler = new NewsHandler( handlerTimer, this );
      handlerTimer.removeCallbacks( newsHandler );
   }

   @Override
   protected void onPause() {
      handlerTimer.removeCallbacks( newsHandler );
      super.onPause();
   }

   @Override
   protected void onResume() {
      handlerTimer.postDelayed( newsHandler, 5000 );
      super.onResume();
   }
}

NewsHandler

public class NewsHandler implements Runnable {
   private static final int THERE_IS_NEWS = 999;
   private Handler timerHandler;
   private Handler newsEventHandler;
   private Context context;

   public NewsHandler( Handler timerHandler, Context context ) {
      this.timerHandler = timerHandler;
      this.newsEventHandler = new NewsEventHandler();
      this.context = context;
   }

   public void run() {
      Message msg = new Message();
      msg.what = THERE_IS_NEWS;
      newsEventHandler.sendMessage( msg );
      timerHandler.postDelayed( this, 5000 );
   }

   private class NewsEventHandler extends Handler { 
      @Override
      public void handleMessage( Message msg ) {
         if( msg.what == THERE_IS_NEWS )
               Toast.makeText( context, "HandlerMessage recieved! There is news!", Toast.LENGTH_SHORT ).show();
      }
   };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!