在上一篇博客Android-sdcard广播的接收处理,中介绍了,如何订阅接收者,去接收系统发送的Sdcard状态改变广播,而这篇博客是订阅接收者,去接收开机/关机的广播

 

Android操作系统在开机的时候,系统会自动发出广播,Android操作系统在关机的时候,系统也会自动发出广播

 

在AndroidManifest.xml订阅接收者

     <!--
            订阅(Xml形式订阅接收者)
            订阅接收者:专门去接收Android系统开机/关机/发出的广播
         -->
        <receiver android:name=".br.MyBootBroadcastReceiver">

            <intent-filter>

                <!-- 开机完成✅ 启动完成✅  开机是危险的行为,需要权限 -->
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <!-- 关机 -->
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />

            </intent-filter>

        </receiver>

 

在AndroidManifest.xml加入关机接收权限

  <!-- 接收开机广播的权限,开机是很危险的行为,所以需要此权限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

 

被订阅的开关机接收者

package liudeli.croadcast1.br;

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

/**
 * 开关机接收者,可以接收两个广播
 * 当Android操作系统开机/关机发生改变后,系统会自动的发出以下两种广播
 *  1.开机广播
 *  2.关机广播
 */
public class MyBootBroadcastReceiver extends BroadcastReceiver {

    private final String TAG = MyBootBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
            Log.d(TAG, "Android操作系统开机了,运行中.......");
        } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
            Log.d(TAG, "Android操作系统关机了.......");
        }
    }
}

 

关机:

 

MyBootBroadcastReceiver: Android操作系统关机了.......

 

 

开机:

12-18 00:35:27.195 1834-1834/liudeli.croadcast1 D/MyBootBroadcastReceiver: Android操作系统开机了,运行中.......