[英]Alarm “onReceive” not being called
我正在嘗試創建一個警報,該警報將修復由於心跳錯誤而導致的與Google Cloud Messaging的丟失連接,請參見此處如何避免Android GCM消息中的延遲/更改心跳
但是,我的警報的onReceive類(設置為每1分鍾進行一次測試)從未被調用。 我查看了與該主題相關的其他幾個問題,所有這些問題都集中在清單中的拼寫和聲明接收者上,我已經檢查了好幾次。
這是所有相關代碼:
MainActivity.java
//Alarm created here
GCMHeartbeatAlarm gcmAlarm = new GCMHeartbeatAlarm();
gcmAlarm.setAlarm(this);
GCMHeartbeatAlarm.java
public class GCMHeartbeatAlarm extends BroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
@Override
public void onReceive(Context context, Intent intent) {
//The part which is supposedly going to fix the GCM connection dropped bug, needs to be called every 5 mins or so via alarm to keep
//GCM connection open
//Commented out for now
// context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
// context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
Log.i("GCMHeartbeat", "GCM Heartbeat Sent!");
}
public void setAlarm(Context context) {
alarmMgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, GCMHeartbeatAlarm.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//Repeat every 1 minute
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), 1000 * 60 * 1 , alarmIntent);
Log.i("GCMHeartbeat", "Alarm set!");
}
}
AndroidManifest.xml
<!-- GCM Heartbeat Alarm Receiver -->
<receiver
android:name="com.MyApp.app.GCMHeartbeatAlarm">
</receiver>
使用此代碼,“警報設置!” 命中日志,但永遠不會命中onReceive登錄。
任何可以幫助我弄清楚發生了什么的事情將不勝感激!
最終成功了。 我不太清楚為什么,但是使用System.currentTimeMillis()不能為triggerAtMillis值工作。 可能是因為警報設置為ELAPSED_REALTIME而不是currentTimeMillis(),所以第一個警報從未觸發。 相反,我使用SystemClock.elapsedRealtime()+ 60 * 1000在設置警報后1分鍾開始觸發警報,然后以1分鍾的間隔開始調用onReceive方法。
工作代碼為:
public void setAlarm(Context context) {
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, GCMHeartbeatAlarm.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 60 * 1000, 60 * 1000, alarmIntent);
Log.e("GCMHeartbeat", "Alarm set!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.