簡體   English   中英

AlarmManager正在阻止主線程

[英]AlarmManager is blocking main thread

我已經實現了一個調用服務的AlarmManager。 問題是,盡管我在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);
    }
} 

我需要異步執行此操作,因為它阻塞了我的主線程。

您可以在AsyncTask中設置警報沒關系。 警報管理器將始終在主線程上啟動您的服務,因為這就是服務的工作方式。

要解決您的問題,您將需要修改警報開始的服務以創建要運行的AsyncTask

我知道不是鏈接服務器場,但Commonsguy編寫了WakeFullIntentService

他明確地使用警報接收器進行了覆蓋。 很棒,值得簽出。 這將使來自警報接收器的請求排隊,在后台運行並喚醒設備,同時在單獨的線程上運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM