一、开机启动
开发者如果有私有app需要开机启动,而且用的技术是处理“android.intent.action.BOOT_COMPLETED”通知,建议在onReceive中睡眠5秒后再发startActivity。
public class BootCompletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
class BootThread implements Runnable {
private Context context;
BootThread(Context context) {
this.context = context;
}
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) { }
Intent intent2 = new Intent(context, app.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
Thread thread = new Thread(new BootThread(context), "BootThread");
thread.start();
}
}
}
以下是和BootCompletedReceiver配对的AndroidManifest.xml示例。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kos.launcher">
...
<application ...>
...
<receiver android:name=".BootCompletedReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>launcher开机启动用的也是处理“android.intent.action.BOOT_COMPLETED”通知,这意味着设备会有两个需要开机启动app。由于两个app启动间隔很短,可能第一个app的主Activity还没执行必要操作,第二个app就运行了,导致第一个app立即被切到后台。举个例子,第一个app是基于SDL写的,它还没创建SDLMain线程,第二个app就运行了,立即被切到后台。留出的5秒时间就是为确保第一个app能完成启动的必要工作。两个app启动顺序上,设备可能无人值守,会要求“最后”是私有app留在前台,为此须要先运行launcher。
为什么要在新线程内执行sleep?——在onReceive所在线程内sleep 5秒,结果是system_process等5秒后再把“android.intent.action.BOOT_COMPLETED”广播给下一个app,这种延时对实现目标没作用。