很多程序都需要在Android开机的时候启动服务,相对的J2ME的麻烦,Android给了我们一个很方便的实现方法。
现在我以我开发的密信软件的开机软件服务COS一下如何实现这个目的。
首先必须有一个BroadcastReceiver以便监听手机开机intent, 而该receiver又负责启动你的service或者activity.
package com.lusgarden.texts.utils;
import com.lusgarden.texts.systems.MainService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootStrService extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(MainService.ACTION_START);
//其中MainService为我要加载的service
//.ACTION_START为一个常量,需在MainService定义,值为"android.intent.action.BOOT_COMPLETED"
i.setClass(context, MainService.class);context.startService(i);
}
}
其次,就需要在Manifest文件中声明一下intent-filter: 先加入使用权限声明:
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
然后加入receiver 注册声明:
- <receiver android:name=".BootStrService" >
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED" />
- </intent-filter>
- </receiver>
- 其实整体来说,安卓还是比较容易开发的移动应用。
- 这样开机后.BootStrService 就能收到开机的intent,然后自动启动我所需要启动的MainService.