AlarmManager is blocking main thread

戏子无情 提交于 2020-01-04 13:37:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!