如何修复Alarm Manager中的错误



我想在我的应用程序中创建一个函数,每5秒发送一次通知:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
final Intent intent = new Intent(getBaseContext(), ShowFormula.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT );
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, pendingIntent);
Log.i(TAG, "started");
}
}); 

这是接收器代码:

@Override
public void onReceive(Context context, Intent intent){
Log.i(TAG, "onReceive working");
if (b) {
Log.i(TAG, "notification started");
makeNotification(context);
}
public void makeNotification(Context context){
Log.i(TAG, "notification continued");
<...notification code...>
}

这是日志:

2020-08-04 18:23:34.451 5492-5492/com.example.learner I/MyApp: started
2020-08-04 18:24:02.074 5492-5492/com.example.learner I/MyApp: onReceive working
2020-08-04 18:24:02.077 5492-5492/com.example.learner I/MyApp: notification started
2020-08-04 18:24:02.077 5492-5492/com.example.learner I/MyApp: notification continued
2020-08-04 18:24:34.455 5492-5492/com.example.learner I/MyApp: onReceive working
2020-08-04 18:24:34.456 5492-5492/com.example.learner I/MyApp: notification started
2020-08-04 18:24:34.456 5492-5492/com.example.learner I/MyApp: notification continued
2020-08-04 18:25:57.792 5492-5492/com.example.learner I/MyApp: onReceive working
2020-08-04 18:25:57.793 5492-5492/com.example.learner I/MyApp: notification started
2020-08-04 18:25:57.793 5492-5492/com.example.learner I/MyApp: notification continued
2020-08-04 18:26:57.804 5492-5492/com.example.learner I/MyApp: onReceive working
2020-08-04 18:26:57.805 5492-5492/com.example.learner I/MyApp: notification started
2020-08-04 18:26:57.805 5492-5492/com.example.learner I/MyApp: notification continued
2020-08-04 18:28:02.358 5492-5492/com.example.learner I/MyApp: onReceive working
2020-08-04 18:28:02.359 5492-5492/com.example.learner I/MyApp: notification started
2020-08-04 18:28:02.359 5492-5492/com.example.learner I/MyApp: notification continued

如您所见,onReceive((以随机间隔调用。哪里会有问题?请帮帮我!

替换

am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, pendingIntent);

带有

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, pendingIntent);

setRepeating是更准确的

相关内容

最新更新