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
AsyncTaskto run in.