我需要一个永远在后台运行的服务来同步我的安卓应用和服务器。我知道如何通过我的应用程序启动它,但是当安卓关闭时,后台服务将会停止。
我该如何做才能保持后台服务始终运行?(即使设备关机然后重新开机...)
我需要将我的后台服务添加到Android的启动程序中。有什么提示吗?
我需要一个永远在后台运行的服务来同步我的安卓应用和服务器。我知道如何通过我的应用程序启动它,但是当安卓关闭时,后台服务将会停止。
我该如何做才能保持后台服务始终运行?(即使设备关机然后重新开机...)
我需要将我的后台服务添加到Android的启动程序中。有什么提示吗?
当设备开启时,使用<action android:name="android.intent.action.BOOT_COMPLETED" />
来启动您的服务。
在AndroidManifest.xml
中:
<receiver android:name=".BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
在你的AndroidManifest.xml
文件中添加权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>
在代码部分BootBroadcastReceiver
中:
public class BootBroadcastReceiver extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
// BOOT_COMPLETED” start Service
if (intent.getAction().equals(ACTION)) {
//Service
Intent serviceIntent = new Intent(context, StartOnBootService.class);
context.startService(serviceIntent);
}
}
}
编辑:如果你是在谈论设备屏幕的开关,那么你需要注册<action android:name="android.intent.action.USER_PRESENT" />
和<action android:name="android.intent.action.SCREEN_ON" />
来在用户在场或屏幕打开时启动你的服务。
(Even when the device turns off and then turns on..
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>
http://blog.gregfiumara.com/archives/82
http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/