我需要始终有一个后台服务来同步我的 Android 应用程序和服务器。我知道如何通过我的应用程序启动它,但是当 Android 关闭时,后台服务就会消失。
如何才能让后台服务始终运行? (即使设备关闭然后再打开......)
我需要将我的后台服务添加到Android的stars程序中。有什么提示吗?
use <action android:name="android.intent.action.BOOT_COMPLETED" />
用于在设备打开时启动您的服务。
In AndroidManifest.xml
:
<receiver android:name=".BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
在您的中添加权限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);
}
}
}
EDIT:如果您正在谈论设备屏幕打开/关闭,那么您需要注册<action android:name="android.intent.action.USER_PRESENT" />
and <action android:name="android.intent.action.SCREEN_ON" />
用于在用户存在或屏幕打开时启动您的服务。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)