手记

APP开机自启动

开机的情况下,android系统会发出一个boot的广播,只需要定义一个broadcastReceiver,接收这个广播,启动相应的service或者activity即可。

public class BootBroadcast extends BroadcastReceiver {
 
    static final String action_boot = "android.intent.action.BOOT_COMPLETED";
 
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(action_boot)) {
 
            // 1.启动自己app里面的activity
            Intent myIntent1 = new Intent(context, MainActivity.class);
            myIntent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myIntent1);
 
            // 2.启动其他app里面的activity或者service
            Intent myIntent2 = context.getPackageManager()
                    .getLaunchIntentForPackage("com.example.usageslidingmenu");
            myIntent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myIntent2);
        }
    }
}

androidmanifest.xml:

<!-- 注册广播接受者--> 
 <receiver android:name="com.app.broadcast.BootBroadcast" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.HOME" />
        </intent-filter>
</receiver>

添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
1人推荐
随时随地看视频
慕课网APP