AlarmManager, BroadcastReceiver and Service not working

前端 未结 3 1210
时光取名叫无心
时光取名叫无心 2021-01-04 05:45

I\'m refactoring some code so that my app will pull data from a website once a day at a given time. From my research, it seems like AlarmManager is the most app

相关标签:
3条回答
  • 2021-01-04 06:28

    You could get AlarmManager to run the Service straight away rather than going through a BroadcastReceiver, if you change your intent like this:

    //Change the intent
    Intent downloader = new Intent(context, MyService.class);
        downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
    //Change to getService()
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
    

    This may solve your problem!

    0 讨论(0)
  • 2021-01-04 06:30

    Instead of using

    Intent dailyUpdater = new Intent(context, MyService.class);

    use

    Intent dailyUpdater = new Intent(this, MyService.class);

    Other suggestion is to start service directly from alarm rather than sending a broadcast and starting the service in broadcast receiver.

    0 讨论(0)
  • 2021-01-04 06:44

    Figured it out!

    MyService should be extending IntentService instead of Service!

    With this change, it also means that instead of overriding onStartCommand should be overriding onHandleIntent instead (see docs on IntentService)

    So MyService now looks like this:

    public class MyService extends IntentService {
    
        public MyService() {
            super("MyServiceName");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d("MyService", "About to execute MyTask");
            new MyTask().execute();
        }
    
        private class MyTask extends AsyncTask<String, Void, boolean> {
            @Override
            protected boolean doInBackground(String... strings) {
                Log.d("MyService - MyTask", "Calling doInBackground within MyTask");
                return false;
            }
        }
    }
    

    Note: From the docs, the default implementation of onBind returns null so no need to override it.

    More information about extending IntentService: http://developer.android.com/guide/topics/fundamentals/services.html#ExtendingIntentService

    0 讨论(0)
提交回复
热议问题