Android开发之实现对闹钟Alarm的控制

随着可穿戴及其他一些辅助设备的出现,在这些设备上实现对Android手机的控制就有了需求,如下图。


Android开发之实现对闹钟Alarm的控制_第1张图片



Android 闹钟应用是在packages/apps/DeskClock下面,查看相关代码发现,闹钟响起的时候会启动一个叫AlarmActivity的类,而这个类注册Receiver来接受广播。


action字符串的定义:

    // AlarmActivity listens for this broadcast intent, so that other applications
    // can snooze the alarm (after ALARM_ALERT_ACTION and before ALARM_DONE_ACTION).
    public static final String ALARM_SNOOZE_ACTION = "com.android.deskclock.ALARM_SNOOZE";

    // AlarmActivity listens for this broadcast intent, so that other applications
    // can dismiss the alarm (after ALARM_ALERT_ACTION and before ALARM_DONE_ACTION).
    public static final String ALARM_DISMISS_ACTION = "com.android.deskclock.ALARM_DISMISS";

receiver的注册:

    IntentFilter filter = new IntentFilter(AlarmService.ALARM_DONE_ACTION);
    filter.addAction(ALARM_SNOOZE_ACTION);
    filter.addAction(ALARM_DISMISS_ACTION);
    registerReceiver(mReceiver, filter);

Receiver的处理动作:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.v("AlarmActivity - Broadcast Receiver - " + action);
            if (action.equals(ALARM_SNOOZE_ACTION)) {
                snooze();
            } else if (action.equals(ALARM_DISMISS_ACTION)) {
                dismiss();
            } else if (action.equals(AlarmService.ALARM_DONE_ACTION)) {
                finish();
            } else {
                Log.i("Unknown broadcast in AlarmActivity: " + action);
            }
        }
    };

发送相应广播就可以实现闹钟的Snooze和Dismiss。



那可穿戴设备如何获取手机上闹钟的状态呢? 其实也是通过接受广播来实现:

    // A public action send by AlarmService when the alarm has started.
    public static final String ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT";

    // A public action sent by AlarmService when the alarm has stopped for any reason.
    public static final String ALARM_DONE_ACTION = "com.android.deskclock.ALARM_DONE";

上面第一条是闹钟响起,第二条就是闹钟被操作。 注册相应的Receiver即可。


你可能感兴趣的:(Android)