我需要一直后台服务,将同步我的Android应用程序和服务器。 我知道如何通过我的应用程序中打开它,但Android的关断时,那么后台服务会死。
我该怎么做才能保持后台服务始终运行? (设备关闭,然后即使当接通...)
我需要添加到我的Android后台服务的启动程序。 任何提示?
我需要一直后台服务,将同步我的Android应用程序和服务器。 我知道如何通过我的应用程序中打开它,但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);
}
}
}
编辑:如果你是在谈论装置画面ON / OFF,那么你需要注册<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..
当完成启动操作系统广播ACTION_BOOT_COMPLETED。 您的应用程序可以要求在您的清单请求允许收到此通知:
<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/