我需要使用Alarm Manager来实现设备重启,我正在调用Intent,然后在Intent活动中使用重启函数。我的设备已经root过了。以下是我的代码:
public void onClick(View v) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calSet.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calSet.set(Calendar.SECOND, 0);
setAlarm(calSet, optRepeat.isChecked());
}});
private void setAlarm(Calendar targetCal, boolean repeat){
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis() , pendingIntent);
if(repeat){
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,targetCal.getTimeInMillis(),
TimeUnit.MINUTES.toMillis(2),pendingIntent);
}else{
alarmManager.set(AlarmManager.RTC_WAKEUP,targetCal.getTimeInMillis(),pendingIntent);
}
}
在AlarmReceiver.java中,我编写的代码如下:
public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
rebootDevice();
}
在清单文件中,我的代码如下:
并且在Manifest文件中,我的代码是这样的
<activity android:name=".activity.RebootTimer" android:label="@string/app_name" android:theme="@android:style/Theme.Dialog" ></activity>
<receiver android:name=".service.AlarmReceiver" />
第一次按我所需求,我的设备正在重新启动,但是在一段时间后,我的设备不再重新启动。当我隐藏重新启动函数时,保持 toast 消息,每个间隔都会显示 toast 消息。
BroadcastReceiver
)未运行,因此无法处理下一个闹钟。相比之下,当您使用Toast
时,您的应用程序没有被杀死,它仍在运行,因此仍在显示Toast
。我找到的解决方案是在启动时运行一个Service
来注册BroadcastReceiver
,参考这里。我还没有测试过,但我相信这应该可以解决问题。 - Andrew T.ACTION_BOOT_COMPLETED
意图过滤器的额外Service
/BroadcastReceiver
来注册(但不调用)你的AlarmReceiver
。 - Andrew T.