开发报警应用

vit*_*han 13 android alarmmanager wakelock commonsware

我想开发一个报警应用程序.应用程序应该像这样工作:

  • 发动它
  • 活动告诉我时间
  • 我可以设置闹钟
  • 我可以关闭申请
  • 当闹钟时间到来时,它会启动一个活动(即使设备被锁定)

我已经尝试调整此示例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);
Run Code Online (Sandbox Code Playgroud)

这是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是服务类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是Manifest中设置服务和接收器的部分:

<receiver android:name=".OnAlarmReceiver"></receiver>
<service android:name=".AlarmService"></service>
Run Code Online (Sandbox Code Playgroud)

永远不会调用doWakefulWork方法!

jon*_*nrz 0

我遇到了类似的问题,我解决了从清单中删除接收器并在代码中设置将其注册到 registerReceiver 的问题。