Android 开机自启动

APP需要开机自启动,要通过开机广播实现。

1,在AndroidManifest.xml中增加权限

    <!-- .接收启动完成的广播权限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2,在AndroidManifest.xml中application标签内增加开机广播

     <receiver
            android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">

            <!--接收启动完成的广播-->
            <intent-filter android:priority="1000">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>

        </receiver>

3,增加开机广播实现类,其中MainActivity.class是开机启动页面

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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lsh670660992/article/details/132733659