实现app开机自启(android静态注册广播接收器)

    动态注册的广播可以自由的控制注册与注销,在activity中定义内部类还可以实现更改ui。但是必须在启动程序之后才能接收到广播。如果要想实现在程序未启动的情况下就能接收广播,需要使用静态注册。

    首先,我们先创建一个广播接收器。右击mainActivity所在的文件夹->New->Other->Broadcast Receiver。会出现一个创建界面。我们将文件命名为BootCompleteReceiver,其中的Exported属性表示是否允许广播接收器接受本程序以外的广播,Enabled属性表示是否启用这个广播接收器。

    其次, 修改BootCompleteReceiver,使其接收到系统的开机广播时,启动MainActivity,代码如下:

public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //Toast.makeText(context,"bbbb", Toast.LENGTH_SHORT).show();
        Intent intent1 = new Intent(context, MainActivity.class);
        context.startActivity(intent1);
    }
}

    系统在启动完成时,会发出一条值为android.intent.action.BOOT_COMPLETED的广播。所以下一步,我们在<intent-filter>里添加相应的action。同时,监听系统开机是需要声明权限的,所以使用<uses-permission>标签又加入一条android.permission.RECEIVE_BOOT_COMPLETED权限。(类似的,以后如果想要接收什么信息,记得添加相应的action(系统的广播有标准的名词记得查明,有些需要权限,记得添加权限,比如接收网络信息))对于开机自启,AndroidManifest.xml代码如下:

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

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

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

    没错结束了,静态本来就是系统提供的嘛,安装完毕开机就会自动打开这个MainActivity界面。自己修改一下intent过滤器,并且改写一下onReceive函数就好。

    那如何发送广播呢,请参考“发送广播

发布了113 篇原创文章 · 获赞 33 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38367681/article/details/105674115
今日推荐