我需要始终有一个后台服务来同步我的 Android 应用程序和服务器.我知道如何通过我的应用程序启动它,但是当 Android 关闭时,后台服务就会死掉.
I need to have ALWAYS a background service that will synchronize my Android application and a server. I know how to launch it through my application, but when the Android turns off, then the background service will die.
如何保持后台服务始终运行?(即使设备关闭然后再打开......)
How can I do to keep the background service always running? (Even when the device turns off and then turns on...)
我需要在 Android 的启动程序中添加我的后台服务.有什么提示吗?
I need to add to the starts programs of Android my background service. Any hints?
推荐答案使用 <action android:name="android.intent.action.BOOT_COMPLETED"/> 来启动你的服务设备开启.
use <action android:name="android.intent.action.BOOT_COMPLETED" /> for starting your service when the device turns on.
在AndroidManifest.xml:
<receiver android:name=".BootBroadcastReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>在您的 AndroidManifest.xml 中添加权限为:
Add permission in your AndroidManifest.xml as:
<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"/> 用于在用户在场或屏幕打开时启动您的服务.
if you are talking about device screen on/off then you need to register <action android:name="android.intent.action.USER_PRESENT" /> and <action android:name="android.intent.action.SCREEN_ON" /> for starting your service when user is present or screen is on.
更多推荐
Android开机时启动后台服务
发布评论