2012-03-13 108 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

他明確使用報警接收器覆蓋它。效果很好,值得一試。這將排隊來自警報接收器的請求,在後臺工作並喚醒設備,同時在單獨的線程上運行。