最近遇到了一个售货机项目。
售货机使用的 android 主板,搭配 20 寸屏幕。
需求是开机直接启动我们开发 APP。
那么就需要监听《手机开机广播》。
在 MainActivity 文件目录下创建文件 BootCompleteReceiver.java 。
放入以下内容,
package 当前目录包名;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
Intent thisIntent = new Intent(context, MainActivity.class);
thisIntent.setAction("android.intent.action.MAIN");
thisIntent.addCategory("android.intent.category.LAUNCHER");
thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(thisIntent);
}
}
}
在 AndroidManifest.xml 中静态注册 刚刚创建的广播接收器。
<!--声明接收启动完成广播的权限-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<!--接收启动完成的广播-->
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
这样 我们的 APP 就能开机自动启动了。但是有点小问题,每次开机会先显示桌面,等个2秒左右才会启动APP。
这和我们的预期是不一样的。商场里面的售货机开机就会启动APP,而不会显示桌面。
想要解决这个问题也很简单,只需要在 AndroidManifest.xml 中将 APP 注册为桌面主题。
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.MONKEY" />
当我们安装好 APP,打开APP,然后重启手机。会显示以下界面,点击你的程序,选择始终允许,以后每次开机手机就自动加载你的 APP 为桌面了。 (PS 网上有人说可以在设置里面搜索桌面主题,然后直接选择你的 APP,但是我这个开发板没有这个选项,暂时用重启的方法将我们的 APP 设置为桌面主题)。