美文网首页APP & program
Android 开机自启动Service

Android 开机自启动Service

作者: vivian310 | 来源:发表于2022-09-07 14:57 被阅读0次

    1、修改AndroidManifest.xml文件

    // 添加接收开机广播的权限
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    // 注册接收开机广播的receiver
    <receiver android:name=".BootBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <category android:name="android.intent.category.LAUNCHER"/>
         </intent-filter>
     </receiver>
    
    //注册需要启动的Service
    <service
        android:name=".TestService"
        android:exported="true"
        android:process="com.test.service">
        <intent-filter>
            <action android:name="com.test.Service" />
        </intent-filter>
    </service>
    

    2、recerver中启动service

    public class BootBroadcastReceiver extends BroadcastReceiver {
        static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_BOOT)){
                Intent mintent = new Intent(context, TestService.class);
                context.startService(mintent);
            }   
        }
    }
    

    3、去掉该服务APP的桌面图标

    正常APP安装后,在Launcher中会显示图标,由于我们的应用是个后台服务,所以不需要显示图标,不显示桌面图标有两种方式

    第一种

    去掉Manifest文件中的<category android:name="android.intent.category.LAUNCHER" />该属性

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>
    </activity>
    

    备注
    这种做法在调试时,不能通过编辑器直接运行,需要编译成APK,再手动安装到设备中。

    第二种

    在activity的<intent-filter>标签中添加<data android:scheme="com.****.****"/>

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            // "com.****.****"为应用包名
            <data android:scheme="com.****.****"/>
        </intent-filter>
    </activity>
    

    备注
    这种做法在调试时,可以直接在编辑器中运行,相对方便一些,两种方式均可以隐藏桌面图标。

    4、将APP放到/system/app目录下

    在Android3.1之后,系统为了加强安全性控制,应用程序安装后或是(设置)应用管理中被强制关闭后处于stopped状态,在这种状态下接收不到任何广播。对于android3.1以后版本,如果要应用接收开机广播有两种方法:
    a).将应用预置到/system/app/目录。
    b).安装应用后先启动一次。(应用只要启动过一次,就不处于stopped状态)

    相关文章

      网友评论

        本文标题:Android 开机自启动Service

        本文链接:https://www.haomeiwen.com/subject/nolonrtx.html