以前,此代码已与WakeFulBroadcast
接收器正常工作,并以此为基础。只是试图设置一个每天在同一时间运行一项服务的警报,如果重新启动设备,该警报将重新启动。
相反,它大约每30-50分钟运行一次,看似随机运行。
MyReceiver.java
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
scheduleAlarms(context);
}
}
static void scheduleAlarms(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyService.class);
PendingIntent scheduledIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (am != null) {
am.cancel(scheduledIntent);
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// if it's after or equal to desired time, then schedule for the next day
// also tried:
// if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 8) {
if (calendar.get(Calendar.HOUR_OF_DAY) >= 8) {
calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
} else {
//Alarm will schedule for today
}
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, scheduledIntent);
}
MyService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sendNotification(getApplicationContext());
return super.onStartCommand(intent, flags, startId);
}
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SharedPreferences boolean that I've omitted
if (!runOnce) {
Log.d("main activity", "First time running app");
editor.putBoolean(RUN_ONCE, true);
editor.commit();
MyReceiver.scheduleAlarms(getApplicationContext());
}
}
Manifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
。 。
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>