想让一个apk开启自动运行,可以通过Android系统中的广播机制实现开机自启动。 广播(Broadcast)是Android系统的四大组件之一,通过该机制可以实现不同应用程序之间的通信。 实现Apk开启自启动,进行如下两步操作即可: 1、添加广播接收器文件: BroadcastReceiver.java
package com.face.detail;
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) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
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);
}
}
}
2、在AndroidManifest.xml文件中设置接收开机广播权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.face.facefeature">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- .接收启动完成的广播权限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:installLocation="internalOnly"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<receiver
android:name=".detail.BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<!--接收启动完成的广播-->
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".detail.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".detail.Activity" />
<activity android:name=".detail.AuthActivity" />
</application>
</manifest>