警报“onReceive”未被调用

时间:2015-08-16 20:00:36

标签: android

我正在尝试创建一个警报,以修复由于心跳错误而导致的与Google云消息传输的丢失连接,请访问此处How to avoid delay in Android GCM messages / change heartbeat

然而,我的闹钟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>

使用此代码,“闹钟设置!” log被命中,但onReceive中的登录永远不会被命中。

任何可以帮助我弄清楚发生了什么的事情都会非常感激!

1 个答案:

答案 0 :(得分:0)

最终让它发挥作用。我不太清楚为什么,但使用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!");
}