0

我試圖用這種方式處理:在BroadcastReceiver開始AlarmManager重複動作,它會發送意向到IntentService,服務寫入日誌。現在,我從日誌中看到,BroadcastReceiver收到意向,啓動AlarmManager,但IntentService從不發生。這裏有什麼可能是錯的?無法修復與AlarmManager通知的IntentService

清單:

<receiver android:name=".wakefullBroadcastReciever.SimpleWakefulReciever" android:enabled="true" android:exported="false"> 
      <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED"/> 
       <action android:name="START"/> 
      </intent-filter> 
     </receiver> 

     <service 
      android:name=".wakefulService.NotificationWakefulIntentService" 
      android:enabled="true"> 
      <intent-filter> 
       <action android:name="NOTIFY_INTENT" /> 
      </intent-filter> 
     </service> 

WakefulReciever:

public class SimpleWakefulReciever extends WakefulBroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (!App.isRunning) { 
      Log.d("wakefull", "start"); 
      Intent startIntent = new Intent(context, NotificationWakefulIntentService.class); 
      startIntent.setAction(Utils.NOTIFY_INTENT); 
      PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startIntent, 0); 
      AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
      am.setRepeating(AlarmManager.RTC_WAKEUP, 
        SystemClock.elapsedRealtime() + 3000, 5000, startPIntent); 
      App.isRunning = true; 
     } 
    } 
} 

IntentService:

public class NotificationWakefulIntentService extends IntentService { 

    public NotificationWakefulIntentService() { 
     super("NotificationWakefulIntentService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     Log.d("time",(System.currentTimeMillis()/1000)+""); 
    } 
} 

回答

0

您定義明確的ServiceIntent,但調用getBroadcast(),而不是getService()

更改如下:

PendingIntent startPIntent = PendingIntent 
    .getBroadcast(context, 0, startIntent, 0); 

要這樣:

PendingIntent startPIntent = PendingIntent 
    .getService(context, 0, startIntent, 0); 

而且,這不是多麼WakefulBroadcastReceiver作品。這是一個幫手類,其目的是提供一個WakeLock,直到您的Service完成其工作。

您無論如何只需延伸WakefulBroadcastReceiverWakeLock保證在onReceive()期間,你什麼也沒有達到。

要回答以下的評論:

您應該設置一個確切的報警,消防每隔一小時(退房this answer),通過調用WakefulBroadcastReceiver.startWakefulService()啓動IntentServiceonReceive(),做你的東西在onHandleIntent(),完成後調用WakefulBroadcastReceiver.completeWakefulIntent()