//第一步,加权限 <!--//允许程序禁用键盘锁--> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <!--允许一个程序接收到 ACTION_BOOT_COMPLETED广播在系统完成启动--> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <!--允许使用PowerManager的 WakeLocks保持进程在休眠时从屏幕消失--> <uses-permission android:name="android.permission.WAKE_LOCK" />
//第二步
<receiver android:name=".utils.ContentReceiver" android:enabled="true" android:exported="true"> <intent-filter android:priority="1234567890987654"> <action android:name="android.intent.action.BOOT_COMPLETED"/> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.HOME" /> </intent-filter> </receiver>
//第三步
public class ContentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 开机后一般会停留在锁屏页面且短时间内没有进行解锁操作屏幕会进入休眠状态,此时就需要先唤醒屏幕和解锁屏幕 // 屏幕唤醒 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "StartupReceiver");//最后的参数是LogCat里用的Tag wl.acquire(); // 屏幕解锁 KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); KeyguardManager.KeyguardLock kl = km.newKeyguardLock("StartupReceiver");//参数是LogCat里用的Tag kl.disableKeyguard(); if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { Log.e("TAG", "onReceive: 开机启动"); //开机启动 Intent mainIntent = new Intent(context, ErWeiMaActivity.class); //在BroadcastReceiver中显示Activity,必须要设置FLAG_ACTIVITY_NEW_TASK标志 mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(mainIntent); } } }