4.8设备重启后启动业务
问题
您在应用中有一项服务,并且希望在手机重新启动后启动。
解
侦听引导事件的意图,并在事件发生时启动服务。
讨论
每当一个平台引导完成,意图被广播与android.intent.action.BOOT_COMPLETED行动。 您需要注册您的应用程序以接收此意图,并请求其权限。 为此,请将以下代码添加到您的AndroidManifest.xml文件中:
对于ServiceManager是接收引导事件的意图的广播接收器,ServiceManager类必须按照示例4-14中所示进行编码。
问题
您在应用中有一项服务,并且希望在手机重新启动后启动。
解
侦听引导事件的意图,并在事件发生时启动服务。
讨论
每当一个平台引导完成,意图被广播与android.intent.action.BOOT_COMPLETED行动。 您需要注册您的应用程序以接收此意图,并请求其权限。 为此,请将以下代码添加到您的AndroidManifest.xml文件中:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
<receiver android:name=".ServiceManager">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
...
对于ServiceManager是接收引导事件的意图的广播接收器,ServiceManager类必须按照示例4-14中所示进行编码。
实例4-14。 BroadcastReceiver实现
public class ServiceManager extends BroadcastReceiver {
Context mContext;
private final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
//All registered broadcasts are received by this
mContext = context;
String action = intent.getAction();
if (action.equalsIgnoreCase(BOOT_ACTION)) {
//check for boot complete event & start your service
startService();
}
}
private void startService() {
//here, you will start your service
Intent mServiceIntent = new Intent();
mServiceIntent.setAction("com.bootservice.test.DataService");
mContext.startService(mServiceIntent);
}
}