繁体   English   中英

即使设置为重复,AlarmManager也仅会首次触发

[英]AlarmManager triggers only the first time even when set to repeating

我现在试图解决这个问题。
在我的活动中,我将警报管理器设置为每2分钟触发一次(用于测试)并通过接收器调用服务。 该服务应该进行网络呼叫等。

我的问题是AlarmManager会第一次正确触发,但永远不会再次触发。 我错过了什么?

在我的活动中,我这样做-

        //Register an alarm manager
        //If no alarm is set
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

        if(!defaultSharedPref.getBoolean("isAlarmSet",false)){
            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime(),
                    R.string.interval,
                    pendingIntent);
            editor = defaultSharedPref.edit();
            editor.putBoolean("isAlarmSet",true);
            editor.commit();
        }

在我的清单上:

<receiver android:process=":remote" android:name=".receiver.AlarmReceiver" />

<service android:name=".service.AlarmService"/>

我的接收器:-

public class AlarmReceiver extends WakefulBroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, AlarmService.class);
        startWakefulService(context,i);
    }
}

我什至尝试了“ setRepeating”,但是没有运气。 它仍然仅触发一次。 有人可以指出我错过了什么吗?

提前致谢。

作为重复计时器的间隔,您要指定资源ID-R.string.interval。 这没有任何意义,但由于是整数,因此可以编译。 如果希望将间隔作为资源使用,则最好使用整数资源,但是最关键的更改是传递资源的实际而不是资源id 因此,请使用Resources.getInteger或getString。

这应该可行,但是我鼓励您完全不要使用字符串资源:

manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
    SystemClock.elapsedRealtime(),
    Integer.parseInt(getResources().getString(R.string.interval)), 
    pendingIntent);`

在实践中看不到任何触发警报的原因是资源ID是非常大的整数,通常在0x8000000范围内,因此您可以有效地设置间隔非常长的周期性警报。 如果您等待一个月左右,则会触发警报。 :-)

如果您想以更灵活的方式安排作业,我建议您使用该库为您摘要使用的计划程序: https : //github.com/evernote/android-job

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM