当Android启动时,会发出一个系统广播,内容为ACTION_BOOT_COMPLETED,它的字符串常量表示为 android.intent.action.BOOT_COMPLETED。我们要做的是做好接收这个消息的准备,而实现的手段就是实现一个BroadcastReceiver。
AndroidManifest.xml文件内容:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.iotts.autostartdemo">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name=".BootBroadcast">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</receiver>
</application>
</manifest>
BootBroadcast文件内容:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31package com.iotts.autostartdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* 文 件 名: BootBroadcast
* 创 建 人:
* 创建日期:
* 修改时间:
* 修改备注:
*/
public class BootBroadcast extends BroadcastReceiver{
private static final String ACTION = "android.intent.action.BOOT_COMPLETED";
private static final String TAG = "StartBroadcastReceiver";
public void onReceive(Context context, Intent intent){
Log.d(TAG,"开机启动了");
if (intent.getAction().equals(ACTION)){
Log.d(TAG,"开机启动了接收到了");
// Intent i = new Intent(context,MainActivity.class);
Intent newIntent = context.getPackageManager()
.getLaunchIntentForPackage("com.iotts.autostartdemo");
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
Log.d(TAG,"开机启动了接收到了");
}
}
}
可以默认创建一个Activity,来测试这段代码