2012-03-13 112 views
2

我已经实现了一个调用服务的AlarmManager。问题是,尽管我在AsyncTask中启动它,但它阻止了主线程。这是我的AsyncTask的来源:AlarmManager阻止主线程

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); 
    } 
} 

我需要异步执行它,因为它阻塞了我的主线程。

回答

7

您在AsyncTask中设置闹钟并不重要。警报管理器将始终在主线程上启动您的服务,因为这是服务的工作原理。

解决您的问题,您将需要修改报警开始创建AsyncTask在运行服务。

+0

我已经在AsincTask中执行了我的服务,它工作正常。非常感谢。 – Alex 2012-03-13 17:24:41

+0

在我的情况下,他们是在服务中的前台通知。我开始通过asynctask进行通知,并且每秒重复使用Timer,但是报警管理器阻止通知,是他们解决此问题的一种方法,请提前致谢 – 2016-11-23 16:04:39

0

我知道,我们不是一个链接农场,但Commonsguy写的WakeFullIntentService

他明确使用报警接收器覆盖它。效果很好,值得一试。这将排队来自警报接收器的请求,在后台工作并唤醒设备,同时在单独的线程上运行。