Android打开时启动后台服务

Fri*_*n3L 7 service android background

我需要总是有一个后台服务来同步我的Android应用程序和服务器.我知道如何通过我的应用程序启动它,但是当Android关闭时,后台服务将会死亡.

如何保持后台服务始终运行?(即使设备关闭然后再打开......)

我需要添加Android的后台服务的启动程序.任何提示?

ρяσ*_*я K 19

使用 <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> 
Run Code Online (Sandbox Code Playgroud)

添加您的权限AndroidManifest.xml:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>
Run Code Online (Sandbox Code Playgroud)

在代码部分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);   
        }   
    }    
}   
Run Code Online (Sandbox Code Playgroud)

编辑:如果您正在谈论设备屏幕开/关,那么当用户在场或屏幕打开时,您需要注册<action android:name="android.intent.action.USER_PRESENT" /><action android:name="android.intent.action.SCREEN_ON" />启动服务.