包名右键->New->Other->Broadcast Receiver,新建一个广播接收器。
public class BootCompleteReceiver extends BroadcastReceiver {
public BootCompleteReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "启动成功", Toast.LENGTH_SHORT).show();
}
}
在AndroidMainfest文件中会自动注册接收器,然后配置权限,接收广播类型:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="top.xiexiaodong.broadcastdemo2">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>