2

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.

kabuko
  • 36,028
  • 10
  • 80
  • 93
Alex
  • 6,957
  • 12
  • 42
  • 48

2 Answers2

7

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.

Brigham
  • 14,395
  • 3
  • 38
  • 48
  • I have executed my Service in a AsincTask and it works fine. Thanks a lot. – Alex Mar 13 '12 at 17:24
  • In my case their is foreground notification in service. I started notification from asynctask and for repeating using Timer every second , but alarm manager blocking notification, is their a way to Fix this, thanks in advance – pavan kvch Nov 23 '16 at 16:04
0

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.

Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61