安卓定时开关机的实现

关于安卓定时开关机,在网上很难找到真正的答案,在这里我引用了其他论坛的解决办法,自己也补充了些。望各位有需要的小伙伴们借鉴。

相对于自动开机来说,自动关机可以在应用层通过设置alarm来实现。而自动开机,网上的介绍就比较少了,因为它需要底层rtc时钟的支持。

1. 简介

我的实现是在设置程序里面增加一个接口,让用户设置自动开关机,这个自动开关机的设置可以参照闹钟的设置。关于自动关机,考虑到关机的时候,用户可能正有一些重要的操作,那么应该给用户一个机会去取消当前的关机。

1)一个BroadcastReceiver, 接收如下信息:

   a) 自定义的ACTION_REQUEST_POWER_OFF:设置auto power off时,通过AlarmManager设置的一个RTC_WAKEUP时钟。当到设置的关机时间时,之前设置到AlarmManager的这个action会被广播。我们实现的这个BroadcastReceiver接收到这个消息后,就要开始power off流程

  b) 自定义的ACTION_REQUEST_POWER_ON:设置auto power on时,通过AlarmManager设置的一个RTC_WAKEUP时钟。我们知道power on的应该设置一个rtc的alarm,那么这个RTC_WAKEUP的alarm是做什么的呢?其实当用户设置自动关机的时候,我设置了2个时钟,一个是RTC时钟,用于关机状态下开机;还有一个就是这个RTC_WAKEUP时钟。之所以设置这个时钟,其实是这样的,比如说你设置了周一到周五每天7点半自动开机,而周四早上你7点就打开了手机,这样到7点半的时候,之前设置的时钟就过期了,如果不重新设置的话,周五早上是不会自动开机的。所以这个时候,之前设置的RTC_WAKEUP就接收到了这样的信息,在重新设置下次自动开机的时钟。

   c) BOOT_COMPLETE和TIMEZONE changed, Time set等时间相关的action:当系统开机完成或时间、时区发生改变时,都需要重新设置alarm。

2)一个处理power off 的Service,当BroadcastReceiver接收到ACTION_REQUEST_POWER_OFF,我们给用户一个机会去取消当前的自动关机。这个Service的作用就是启动一个无背景的页面,给用户提示。同时播放之前用户设置的提示音或振动。

3)一个Activity:显示一个dialog提示用户要自动关机,并用一个计时器倒计时。当用户确认关机,或者计时器到时间的时候,就关机。否则取消当前关机,并重设下次自动关机alarm。

2. 自动关机的实现

自动关机的实现比较简单,这里主要说一下怎么设置alarm,和实现关机:

1) 设置自动关机的alarm:

AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(
                "com.android.settings.action.REQUEST_POWER_OFF");

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
2)自动关机掉的是 ./frameworks/base/services/java/com/android/server/ShutdownActivity.java:

        Intent newIntent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
        newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(newIntent);
Intent.ACTION_REQUEST_SHUTDOWN是Intent里面一个隐藏的action。


3. 自动开机的实现

一直在做上层应用和framework,对于底层不是很熟悉。正好有同事之前做过关机闹铃,所以把他之前的实现稍加改动就可以了。在系统power off的状态下自动开机,我们需要设置一个rtc时钟,当用户设置自动开机时,由AlarmManagerService将时钟设置下去。这里需要底层的支持。这里的实现是定义一个我们自己的rtc alarm type:

1) 首先要在头文件里面定义:

   a) kernel/include/linux/android_alarm.h

#define ANDROID_ALARM_GET_TIME(type)        ALARM_IOW(4, type, struct timespec)
#define ANDROID_ALARM_SET_RTC               _IOW('a', 5, struct timespec)

/* we define ANDROID_RTC_ALARM_SET for auto power off */
#define ANDROID_RTC_ALARM_SET               _IOW('a', 7, int)

#define ANDROID_ALARM_BASE_CMD(cmd)         (cmd & ~(_IOC(0, 0, 0xf0, 0)))
b) bionic/libc/kernel/common/linux/android_alarm.h

#define ANDROID_RTC_ALARM_SET _IOW('a', 7, int)
2) 定义完成之后,还需要实现:在kernel/drivers/rtc/alarm-dev.c文件的alarm_ioctl方法里面,增加一个case,实现设置alarm

case ANDROID_RTC_ALARM_SET:
        {
            unsigned int rtc_alarm_time;
            struct rtc_time rtc_now;
            if (copy_from_user(&rtc_alarm_time, (void __user *)arg,
                sizeof(rtc_alarm_time))) {
                rv = -EFAULT;
                goto err1;
            }
            if (pmic_rtc_get_time(&rtc_now) < 0) {
                rtc_now.sec = 0;
                if (pmic_rtc_start(&rtc_now) < 0) {
                    printk("get and set rtc info failed\n");
                    break;
                }
            }
            pmic_rtc_disable_alarm(PM_RTC_ALARM_1);
            rtc_now.sec += rtc_alarm_time;
            pmic_rtc_enable_alarm(PM_RTC_ALARM_1, &rtc_now);
            break;
        }
增加一个include:

#include <mach/pmic.h>
3)在frameworks/base/services/jni/com_android_server_AlarmManagerService.cpp里面增加一个方法去设置时钟:
static void android_server_AlarmManagerService_updateRtcAlarm(JNIEnv* env, jobject obj, jint fd, jint seconds)
{
#if HAVE_ANDROID_OS
    int result = ioctl(fd, ANDROID_RTC_ALARM_SET, &seconds);
    LOGE("set rtc alarm to %d later: %s\n", seconds, strerror(errno));
    if (result < 0)
    {
        LOGE("Unable to set rtc alarm to %d later: %s\n", seconds, strerror(errno));
    }
#endif
}
定义一下接口:
{"updateRtcAlarm", "(II)V", (void*)android_server_AlarmManagerService_updateRtcAlarm}

4) 在frameworks/base/services/java/com/android/server/AlarmManagerService.java里面定义native的设置alarm的方法,然后调用就可以实现将自动关机的alarm设置下去了:

定义:private native void updateRtcAlarm(int fd, int seconds);

调用:

public void setRepeating(int type, long triggerAtTime, long interval, 
            PendingIntent operation) {
        if (operation == null) {
            Slog.w(TAG, "set/setRepeating ignored because there is no intent");
            return;
        }
        synchronized (mLock) {
            Alarm alarm = new Alarm();
            alarm.type = type;
            alarm.when = triggerAtTime;
            alarm.repeatInterval = interval;
            alarm.operation = operation;

            // Remove this alarm if already scheduled.
            removeLocked(operation);

            if (localLOGV) Slog.v(TAG, "set: " + alarm);

            int index = addAlarmLocked(alarm);
            if (index == 0) {
                setLocked(alarm);
            }

            // Start to setup auto power on alarm
            if ((alarm.type == AlarmManager.ELAPSED_REALTIME_WAKEUP) && 
                                alarm.operation.getTargetPackage().equals("com.android.settings")) {
                updateRtcAlarm(mDescriptor, (int)((alarm.when - System.currentTimeMillis()) / 1000));
            }
            // End to setup auto power on alarm
        }
    }
5)在应用层设置自动开机
AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(
                "com.android.settings.action.REQUEST_POWER_ON");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, pendingIntent);


4. 总结

1) 自动开机原理比较简单,但是需要底层的支持,所以对于做应用或者framework层的技术人员来说,实现起来稍微比较麻烦。
2) 在设置自动开关机的时候,需要考虑的情况很多,比如是否设置时间/时区的改变,手机当前是开机还是关机状态等。


5. 拓展(定时开关机)
有时候,会有这样的需求:定时设置开关机时间。这里我给出一个思路,可以利用数据库来进行操作。
对于定时关机,可以将关机数据存入数据库,然后开启一个后台服务,定时的对数据库进行查询,获取到当前的系统时间再和关机时间做对比,到了关机时间则发送广播,通知系统,执行关机。
对于定时开机,我们在关机之前,同样利用数据库,将下次开机时间设置到自动开机的代码里(上述所示),下次开机同样开启服务,定时查询数据库。这样不管你设置了多少开关机的时间段,都能反复执行,多次定时。





### 回答1: Android系统定时开实现的方法有多种,下面我将以300字介绍一种较为常用的方法。 首先,我们需要在Android系统中注册一个定时任务,使得系统在特定的时间点自动开。我们可以利用AlarmManager类来完成该任务。 1.在AndroidManifest.xml文件中注册权限: <uses-permission android:name="android.permission.REBOOT" /> 2.创建一个BroadcastReceiver类,用于接收定时任务触发的广播: public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { // 执行你想要的操作 } } } 3.在AndroidManifest.xml文件中注册BroadcastReceiver: <receiver android:name=".BootReceiver" android:enabled="true" android:exported="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> 4.在你的代码中使用AlarmManager类来触发定时任务: // 获取AlarmManager实例 AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // 创建一个PendingIntent,用于触发定时任务 Intent intent = new Intent(getApplicationContext(), BootReceiver.class); intent.setAction(Intent.ACTION_BOOT_COMPLETED); PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // 设置定时任务的触发时间,这里以每天8点为例 Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 8); calendar.set(Calendar.MINUTE, 0); // 设置定时任务,使用AlarmManager的set方法 // 参数1:定时任务的类型,这里使用RTC_WAKEUP,表示在系统的实时时钟(RTC)时间触发任务,即在系统休眠的情况下也会唤醒系统执行任务 // 参数2:定时任务的触发时间 // 参数3:定时任务触发时的PendingIntent alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent); 以上就是一种实现Android定时开的方法,通过注册BroadcastReceiver接收系统开广播,再通过AlarmManager类设置定时任务的触发时间,来实现定时开功能。 ### 回答2: Android系统中,定时开功能可以通过编程的方式来实现。下面我将简要介绍一种实现方法。 首先,我们需要编写一个广播接收器,用于接收定时开的广播。在该广播接收器中,我们可以设置定时开的具体时间,当达到设定时间时,系统会发送一条开广播。我们需要在接收到该广播时,执行我们所需的操作,比如启动指定的应用程序或者执行一段特定的代码。 接下来,我们需要在AndroidManifest.xml文件中注册该广播接收器。在文件中的<application>标签内,添加以下代码: ```xml <receiver android:name=".BootReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver> ``` 这里的`.BootReceiver`需要根据你的广播接收器的包名和类名进行适当的修改。 至此,我们已经完成了定时开的基本设置。当设定的时间到达时,系统会发送`android.intent.action.BOOT_COMPLETED`广播,我们的应用程序会收到此广播并执行相应的操作。 需要注意的是,为了使广播接收器能够接收到开广播,需要添加权限:`<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>`。 希望这个简单的介绍能对你有所帮助! ### 回答3: Android定时开可以通过编写一个定时任务,实现设备在指定的时间自动开。可以按照以下步骤进行操作: 1. 在AndroidManifest.xml文件中添加一个权限声明,以便访问系统的休眠状态。 ```xml <uses-permission android:name="android.permission.DEVICE_POWER" /> ``` 2. 创建一个BroadcastReceiver类来接收开广播。 ```java public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 在这里编写设备开后自动执行的操作 } } ``` 3. 在AndroidManifest.xml文件中注册广播接收器,以便在开时接收广播。 ```xml <receiver android:name=".BootReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> ``` 4. 在你需要的地方设置定时开的时间。可以使用AlarmManager来实现定时操作。 ```java // 获取AlarmManager实例 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // 设置开时间,这里以每天早上6点为例 Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 6); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); // 设置定时任务 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); ``` 这样,当设备关后,系统会在指定的时间自动开,并触发BootReceiver接收器的onReceive方法,你可以在该方法中编写设备开后自动执行的操作。 需要注意的是,有些设备可能会对定时开进行限制,可能无法在所有的设备上都完全实现定时开功能。因此,在实际应用中,需要检查设备的系统版本,并确保该设备支持定时开功能。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值