AlarmManager, BroadcastReceiver and Service not working

前端 未结 3 1209
时光取名叫无心
时光取名叫无心 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: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 {
            @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

提交回复
热议问题