android开机自启动的后台Service的实现 .
16lz
2022-05-31
在Manifest.xml文件中注册广播接收器,接收开机广播 [html] view plain copy print ?
2.广播接收器接收到开机广播后启动Service [java] view plain copy print ?
3.在Service里面做要做的事情 [java] view plain copy print ?
这个工程没有Activity,所有安装上以后也看不见。
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="com.sensor.demo"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-sdkandroid:minSdkVersion="7"/>
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name">
- <serviceandroid:name=".SensorFunctionService"></service>
- <receiverandroid:name=".BootCompletedReceiver">
- <intent-filter>
- <actionandroid:name="android.intent.action.BOOT_COMPLETED"/>
- </intent-filter>
- </receiver>
- </application>
- </manifest>
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sensor.demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <service android:name=".SensorFunctionService"></service> <receiver android:name=".BootCompletedReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application></manifest>
2.广播接收器接收到开机广播后启动Service [java] view plain copy print ?
- publicclassBootCompletedReceiverextendsBroadcastReceiver{
- @Override
- publicvoidonReceive(Contextcontext,Intentintent){
- //TODOAuto-generatedmethodstub
- IntentmIntent=newIntent(context,SensorFunctionService.class);
- context.startService(mIntent);
- }
- }
public class BootCompletedReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub Intent mIntent = new Intent(context, SensorFunctionService.class); context.startService(mIntent);}}
3.在Service里面做要做的事情 [java] view plain copy print ?
- publicclassSensorFunctionServiceextendsService{
- @Override
- publicvoidonCreate(){
- super.onCreate();
- }
- @Override
- publicIBinderonBind(Intentarg0){
- returnnull;
- }
- }
public class SensorFunctionService extends Service { @Overridepublic void onCreate() {super.onCreate();} @Overridepublic IBinder onBind(Intent arg0) {return null;}}
这个工程没有Activity,所有安装上以后也看不见。
要做的事情需要在重启机器后方能执行,因为Service的启动需要一个开机广播。
更多相关文章
- Android监听来电/挂断/接听
- Android(安卓)无法接收开机广播的问题
- Android关闭开机弹出SIM卡变动提示对话框
- android 锁屏页
- 蓝牙原理Android代码实现
- [Android]BroadcastQueue如何分发广播(四)
- 通过广播检测sdcard插拔操作
- Android锁屏及监听锁屏事件
- Android中获取电池电量