android app 开机自启服务
Posted On 2014年9月4日
1. 首先写一个service服务。
2. 写一个receiver , 当接受到开机的事件后,便启动服务。
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent myIntent = new Intent(context, YourService.class); context.startService(myIntent); } }
3. AndroidManifest.xml: 将获取开机事件的权限加上以及设定 receiver 过滤条件。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.broadcast.receiver.example" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> <activity android:name=".BR_Example" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Declaring broadcast receiver for BOOT_COMPLETED event --> <receiver android:name=".MyReceiver " android:enabled="true" android:exported="false"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> </manifest>
此篇文章已被阅读2189 次