android APP開機自動啟動

yingxian_Fei發表於2016-06-06

1.編寫目標類並繼承BroadcastReceiver

package com.example.gsensortester;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootCompletedReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		final Context mContext = arg0;
		Log.d("BootCompletedReceiver", "recevie boot completed ... ");  
		if(Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction()))  {
                     Log.d("BootCompletedReceiver", "Hello,world... ");
               }			
	}

}

上列在收到開機廣播之後輸出"Hello,world".

2.AndroidManifest.xml中新增許可權和註冊

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gsensortester"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
		<receiver android:name=".BootCompletedReceiver">  
		    <intent-filter>    
		        <action android:name="android.intent.action.BOOT_COMPLETED" />
		        <category android:name="android.intent.category.DEFAULT" />    
		    </intent-filter>  
		</receiver>         
    </application>

</manifest>

主要是向其中註冊廣播接收器:

		<receiver android:name=".BootCompletedReceiver">  
		    <intent-filter>    
		        <action android:name="android.intent.action.BOOT_COMPLETED" />
		        <category android:name="android.intent.category.DEFAULT" />    
		    </intent-filter>  
		</receiver> 
以及新增開機廣播接收的許可權:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />


相關文章