App实现开机启动

时间:2021-09-30 04:45:24

Android启动时,会发出一个系统广播 ACTION_BOOT_COMPLETED,它的字符串常量表示为 “android.intent.action.BOOT_COMPLETED”

开机自启动程序,只需要“捕捉”到这个消息再启动你的程序即可,我们要做的是接收这个消息,并实现一个BroadcastReceiver。

1.添加一个自定义广播类 BootReceiver

public class BootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { // boot
Intent intent2 = new Intent(context, MainActivity.class);
// intent2.setAction("android.intent.action.MAIN");
// intent2.addCategory("android.intent.category.LAUNCHER");
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
}

2.在AndroidManifest.xml中Application节点内,添加自定义的广播类和权限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moumou.sharedpreferencetest">
<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=".BootReceiver" >  //自定义广播类
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />

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