简体   繁体   English

AlarmManager正在阻止主线程

[英]AlarmManager is blocking main thread

I have implemented an AlarmManager which calls a Service. 我已经实现了一个调用服务的AlarmManager。 The problem is that although I'm launching it in AsyncTask, it's blocking the main thread. 问题是,尽管我在AsyncTask中启动它,但它阻塞了主线程。 This is the source of my AsyncTask: 这是我的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. 您可以在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. 要解决您的问题,您将需要修改警报开始的服务以创建要运行的AsyncTask

I know were not a link farm but Commonsguy wrote the WakeFullIntentService 我知道不是链接服务器场,但Commonsguy编写了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. 这将使来自警报接收器的请求排队,在后台运行并唤醒设备,同时在单独的线程上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM