当安卓系统启动时如何启动后台服务

8

我需要一个永远在后台运行的服务来同步我的安卓应用和服务器。我知道如何通过我的应用程序启动它,但是当安卓关闭时,后台服务将会停止。

我该如何做才能保持后台服务始终运行?(即使设备关机然后重新开机...)

我需要将我的后台服务添加到Android的启动程序中。有什么提示吗?

2个回答

23

当设备开启时,使用<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" />来在用户在场或屏幕打开时启动你的服务。


当我打开我的手机时,出现了一个错误:“应用程序被强制...”。它无法正常工作。 - Frion3L

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接