问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/9687557/alarmmanager-is-blocking-main-thread