android开机自启动的后台Service的实现

1.在Manifest.xml文件中注册广播接收器,接收开机广播

<?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

public class BootCompletedReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
        Intent mIntent = new Intent(context, SensorFunctionService.class);
        context.startService(mIntent);
	}
}

3.在Service里面做要做的事情

public class SensorFunctionService extends Service {   	

    @Override
	public void onCreate() {
		super.onCreate();
	}
    
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}

这个工程没有Activity,所有安装上以后也看不见。

要做的事情需要在重启机器后方能执行,因为Service的启动需要一个开机广播。





你可能感兴趣的:(android,service,application,Class,action,encoding)