简体   繁体   中英

AlarmManager is blocking main thread

I have implemented an AlarmManager which calls a Service. The problem is that although I'm launching it in AsyncTask, it's blocking the main thread. This is the source of my AsyncTask:

private class NotificationsServiceTask extends AsyncTask<Void, Void, Void> {
    private AlarmManager alarmMgr;
    private PendingIntent pi;

    @Override
    protected Void doInBackground(Void... params) {
        alarmMgr = (AlarmManager) LoginActivity.this.getSystemService(Context.ALARM_SERVICE);
        Intent serviceIntent = new Intent(LoginActivity.this, Service.class);
        pi = PendingIntent.getService(LoginActivity.this, 0, serviceIntent, 0);
        alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 120000, pi);
        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
} 

I need to do it asynchronously because it's blocking my main thread.

It doesn't matter that you set the alarm in an AsyncTask. The alarm manager will always start your service on the main thread, because that's how services work.

To fix your problem, you will need to modify the service that the alarm is starting to create an AsyncTask to run in.

I know were not a link farm but Commonsguy wrote the WakeFullIntentService

He explicity covers it using an Alarm reciever. works great, worth checkin out. That will queue requests from your alarm receiver, work in the background and wake the device, whilst running on a separate thread.

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