前提:
https://developer.android.com/guide/components/activities/background-starts#exceptions此处列出了多种允许的情况,此处仅列举以下情况:
“应用程序已获得SYSTEM_ALERT_WINDOW用户授予的权限。”
你的应用必须手动授权SYSTEM_ALERT_WINDOW(悬浮窗权限)
注意:在Android 10的Go版本上运行的应用 无法获得该SYSTEM_ALERT_WINDOW权限。
可通过如下方式吊起设置页面(可选),也可以手动去找到该应用授权:
private void startSystemAlertWindowPermission() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Log.i("test", "[startSystemAlertWindowPermission] requesting system alert window permission.");
startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())));
}
}
} catch (Exception e) {
Log.e("test", "[startSystemAlertWindowPermission] error:", e);
}
}
1:AndroidManifest.xml:
声明权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
在application的receiver标签中:
<receiver android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
2:BootBroadcastReceiver.java:
package com.xiaoyvxian.testerlab;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);
}
}
}
- 安装并启动应用:确保应用至少启动过一次,以注册
BroadcastReceiver
。 - 重启设备:通过重启设备触发
BOOT_COMPLETED
广播。 - 验证启动:观察设备启动后,应用是否在前台启动并显示
MainActivity
。
参考文档:https://developer.android.com/guide/components/activities/background-starts