我想开发一个警报应用程序。应用程序应该像这样工作:
- 启动它
- 活动告诉我时间
- 我可以设置闹钟
- 我可以关闭应用程序
- 当闹钟时间到来时,它会启动一个活动(即使设备被锁定)
我已尝试调整此示例https://github.com/commonsguy/cwac-wakeful但在闹钟时间到来时我无法启动活动。
我使用此代码设置警报(为了测试,我已在活动方法中插入此代码onCreate
):
Intent intent = new Intent(this, OnAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
这是 OnAlarmReceiver 类:
public class OnAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(ClockActivity.LOG_TAG, "OnAlarmReceiver::onReceive");
WakefulIntentService.sendWakefulWork(context, AlarmService.class);
}
}
这是服务类:
public class AlarmService extends WakefulIntentService {
public AlarmService(String name) {
super(name);
}
@Override
protected void doWakefulWork(Intent intent) {
Log.i(ClockActivity.LOG_TAG, "AlarmService::doWakefulWork");
Intent newIntent = new Intent(getApplicationContext(), ClockActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.setAction(ClockActivity.ALARM_ACTION);
getApplicationContext().startActivity(newIntent);
}
}
这是 Manifest 中设置服务和接收器的部分:
<receiver android:name=".OnAlarmReceiver"></receiver>
<service android:name=".AlarmService"></service>
doWakefulWork 方法永远不会被调用!