有关Android 的开机启动权限 - eju-front/mobile-solution GitHub Wiki
开机启动不属于运行时权限,在安装时就能自动获得
按照以下的 AndroidManifest.xml 进行配置,在 小米M4 (4.4.4), 三星S7 (6.0.1), 三星S4(5.0.1) 都测试通过,可以直接获得权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo123">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
如果想在运行时查询是否拥有权限及弹出窗口申请权限可以调用以下代码
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_PERMISSION = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECEIVE_BOOT_COMPLETED) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_BOOT_COMPLETED},
REQUEST_PERMISSION);
} else {
System.out.println("Permission is already granted");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
int len = permissions.length;
for (int i = 0; i < len; i++) {
String permission = permissions[i];
boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
System.out.println(String.format("Permission '%s' is granted or not: %s", permission, granted));
}
}
}
}