【原理】
当Android系统完成BOOT阶段之后,就会发送一条名为 ACTION_BOOT_COMPLETED 的广播,我们便可在一个BroadcastReceiver中捕获这条广播,然后启动我们的Activity或者Service,当然要注意的是,我们的application必须具有捕获该广播的权限,下面请看具体步骤:
【步骤一】首先要有一个用于开机启动的Activity或者Service,这里以系统自己创建的最简单的Activity为例进行讲解。
package com.billhoo.study; import android.app.Activity; import android.os.Bundle; public class BootTestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
【步骤二】我们要编写一个BroadcastReceiver用以捕获ACTION_BOOT_COMPLETED这条广播,并在捕获之后启动我们要启动的Activity。
注意:必须在intent中添加 Intent.FLAG_ACTIVITY_NEW_TASK 标记,
package com.billhoo.study; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { Intent newIntent = new Intent(context, BootTestActivity.class); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //注意,必须添加这个标记,否则启动会失败 context.startActivity(newIntent); } } }
【步骤三】在AndroidManifest.xml配置文件中注册我们的BroadcastReceiver
<receiver android:name=".BootCompletedReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
【步骤四】在AndroidManifest.xml配置文件中添加允许我们捕获该广播的权限
<!-- permissions --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
重启虚拟机,大功告成。
下面附上完成的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.billhoo.study" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="4" /> <!-- permissions --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <!-- activities --> <activity android:name=".BootTestActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- receivers --> <receiver android:name=".BootCompletedReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> </manifest>