Android Service、activity开机自启

最近在写一个关于开机自启的后台服务,在这里做个总结。

测试环境:

Anroid 4.4(LG)

Android 6.0(小米4)

ROOT权限

代码分析:

程序开机自启需要监听系统开机时发出的广播,安装在SD的应用无法启动,因为开机广播发出后才加载SD卡:

android.intent.action.BOOT_COMPLETED

 监听广播需要在AndroidManifest添加接收广播的权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

 添加权限后新建一个广播接收类,继承BroadcastReceivcer,实现它的onReceive

public class BootBroadcastReceiver extends BroadcastReceiver {

    static final String ACTION = "android.intent.action.BOOT_COMPLETED";
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(ACTION)){
            Log.e("Broadcast","接收到开机广播广播");
//            Intent myIntent = new Intent(context, MainActivity.class);
//            myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(myIntent);  //启动Activy

            Intent myIntent = new Intent(context, SendService.class);
            context.startService(myIntent);  //启动Service
            //com.wn.readfile.destroy 为自定义的广播,在程序执行onDestroy的时候发出
        }else if (intent.getAction().equals("com.wn.readfile.destroy")){
            Intent intent1 = new Intent(context,SendService.class);
            context.startService(intent);
        }
    }
}

AndroidManifest中注册新建广播接收类:

<receiver android:name="com.wn.readfile.BootBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="1000">
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.USER_PRESENT"/>
                <action android:name="com.wn.readfile.destroy"/>
            </intent-filter>
</receiver>

机器人:能是指该类是否能够被实例化,默认为

Android的:出口是指该类是否能够被其它应用程序组件调用

安卓:优先级是接收广播的优先级,数越大优先级越高,优先级相同的,执行顺序随机。

<action android:name =“”/> 是广播注册,为该BootBroadcastReceiver类监听该广播

android.intent.action.BOOT_COMPLETED 是开机是发出的广播

android.intent.action.USER_PRESENT 是用户解锁屏幕时的广播

com.wn.readfile.destroy 是开发者自定义的广播,通过sendBroadcast(intent)发送

为了让程序一直运行,在自定义的服务类或者活动中的的onDestroy中发送自定义的广播到广播接收类:

    @Override
    public void onDestroy() {
        stopForeground(true);
        Intent intent = new Intent("com.example.demo.destroy");
        sendBroadcast(intent);
        Log.e("test","服务销毁后重启");
        super.onDestroy();
    }

使用adb shell命令模拟发送开机广播,命令:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

通过以上的步骤就可以成功自启了,但!划重点!要考试!

Service的启动,必须​​手动启动一次程序才可以一直运行.Android 4.4亲测可用。

在小米4 Android6.0中,需要授权程序开机自启,本次测试中,接触到网络方面,程序开机自启后,数据发送不出去,是因为小米的MIUI中有个神隐功能,开机时限制了程序的各种功能,因此网络无法连接,找到小米的神隐模式,将应用设为无限制即可。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值