首页 > 代码库 > Android 开机自动启动服务

Android 开机自动启动服务

在前面的文章中提到了remote service 的创建过程,现在我们要让它开机自动启动

 

1.在前面代码的基础上添加 RemoteServiceBootReceiver.java ,实现一个intent的receiver

[java] view plaincopyprint?
  1. package com.fly;  
  2. import android.content.BroadcastReceiver;  
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. import android.util.Log;  
  6. public class RemoteServiceBootReceiver extends BroadcastReceiver {  
  7.     private static final String TAG = "U0fly RemoteServiceBootReceiver";  
  8.     static final String ACTION = "android.intent.action.BOOT_COMPLETED";  
  9.     @Override  
  10.     public void onReceive(Context arg0, Intent arg1) {  
  11.         Log.d(TAG, "Boot completed");  
  12.         // TODO Auto-generated method stub  
  13.         if (arg1.getAction().equals(ACTION)) {  
  14.             // service  
  15.             Intent myintent = new Intent(arg0, RemoteService.class);  
  16.             myintent.setAction("com.fly.RemoteService");  
  17.             arg0.startService(myintent);  
  18.         }  
  19.     }  
  20. }  

 

 

2.在AndroidManifast.xml中添加权限,并注册一个receiver

[java] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.fly" android:versionCode="1" android:versionName="1.0">  
  4.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  5.         <activity android:name=".RemoteServiceActivity"  
  6.             android:label="@string/app_name">  
  7.             <intent-filter>  
  8.                 <action android:name="android.intent.action.MAIN" />  
  9.                 <category android:name="android.intent.category.LAUNCHER" />  
  10.             </intent-filter>  
  11.         </activity>  
  12.         <service android:name="RemoteService">  
  13.             <intent-fliter>  
  14.                 <action android:name="com.fly.RemoteService" />  
  15.             </intent-fliter>  
  16.         </service>  
  17.       
  18.         <receiver android:name=".RemoteServiceBootReceiver">  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.BOOT_COMPLETED" />  
  21.             </intent-filter>  
  22.         </receiver>  
  23.           
  24.     </application>  
  25.       
  26.     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>   
  27.     <uses-sdk android:minSdkVersion="7" />  
  28. </manifest>