Android开机自启动Service实现详解

Ianthe ·
更新时间:2024-05-16
· 1747 次阅读

目录

1、修改AndroidManifest.xml文件

2、recerver中启动service

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

第一种

第二种

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

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实现详解的详细内容,更多关于Android 开机自启动Service的资料请关注软件开发网其它相关文章!



service Android

需要 登录 后方可回复, 如果你还没有账号请 注册新账号