启动后台服务的Android导通时 [英] Starting background service when Android turns on
问题描述
我需要一直后台服务,将同步我的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?
推荐答案
使用<作用机器人:名字=android.intent.action.BOOT_COMPLETED/>
启动您的服务时设备TUR非
use <action android:name="android.intent.action.BOOT_COMPLETED" />
for starting your service when device tur non
在清单的.xml
<receiver android:name=".BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
在允许添加的表现为:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>
在code部分BootBroadcastReceiver:
in code part 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);
}
}
}
编辑:如果你正在服用有关设备屏幕的开/关,那么你需要注册 &lt;作用机器人:名字=android.intent.action.USER_ preSENT/&GT;
和&lt;作用机器人:名字=android.intent.action.SCREEN_ON/&GT;
用于启动服务当用户为present或屏幕上
EDIT : if you are taking 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导通时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!