静态注册实现开机启动

动态注册的广播接收器可以自由地控制注册与注销, 在灵活性方面有很大的优势, 但是它也存在着一个缺点, 即必须要在程序启动之后才能接收到广播, 因为注册的逻辑是写在onCreate() 方法中的。 那么有没有什么办法可以让程序在未启动的情况下就能接收到广播呢? 这就需要使用静态注册的方式了。

这里我们准备让程序接收一条开机广播, 当收到这条广播时就可以在onReceive() 方法里执行相应的逻辑, 从而实现开机启动的功能。 可以使用Android Studio提供的快捷方式来创建一个广播接收器,

右击com.example.broadcasttest包→New→Other→Broadcast Receiver

Exported 属性表示是否允许这个广播接收器接收本程序以外的广播,

Enabled 属性表示是否启用这个广播接收器

然后修改BootCompleteReceiver中的代码

public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Boot Complete", Toast.LENGTH_LONG).show();
    }
}Code language: PHP (php)

另外, 静态的广播接收器一定要在AndroidManifest.xml文件中注册才可以使用, 不过由于我们是使用Android Studio的快捷方式创建的广播接收器, 因此注册这一步已经被自动完成了。 打开AndroidManifest.xml文件瞧一瞧

不过目前BootCompleteReceiver还是不能接收到开机广播的, 我们还需要对AndroidManifest.xml文件进行修改才行

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

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

    <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=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>Code language: HTML, XML (xml)

由于Android系统启动完成后会发出一条值为android.intent.action.BOOT_COMPLETED的广播, 因此我们在<intent-filter> 标签里添加了相应的action。 另外, 监听系统开机广播也是需要声明权限的, 可以看到, 我们使用<uses-permission> 标签又加入了一条android.permission.RECEIVE_BOOT_COMPLETED 权限。

Previous:

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注