1.首先开机启动后系统会发出一个Standard Broadcast
Action,名字叫android.intent.action.BOOT_COMPLETED,这个Action只会发出一次。
2.构造一个IntentReceiver类,重构其抽象方法onReceiveIntent(Context
context, Intent intent),在其中启动你想要启动的Service。
3.在AndroidManifest.xml中,首先加入来获得BOOT_COMPLETED的使用许可,然后注册前面重构的IntentReceiver类,在
其中加入 ,以使其能捕捉到这个Action。
Xml代码  
- android:name="android.permission.RECEIVE_BOOT_COMPLETED">
- android:name=".OlympicsReceiver"
android:label="@string/app_name">
-
-
android:name="android.intent.action.BOOT_COMPLETED"
/>
-
android:name="android.intent.category.LAUNCHER"
/>
-
-
Java代码
- public
class OlympicsReceiver extends BroadcastReceiver
- {
-
-
static final String ACTION
= "android.intent.action.BOOT_COMPLETED";
-
-
public void onReceive(Context context, Intent
intent)
-
{
-
if
(intent.getAction().equals(ACTION))
-
{
-
context.startService(new Intent(context,
-
OlympicsService.class),
null);//启动倒计时服务
-
Toast.makeText(context, "OlympicsReminder service has
started!",
Toast.LENGTH_LONG).show();
-
//这边可以添加开机自动启动的应用程序代码
-
}
-
}
- }
为了不变成流氓软件,在自己的应用中加上设置可以开机自启动的选项,默认是不是自启动就要看具体应用的要求了。
|