Android开机时启动后台服务 [英] Starting background service when Android turns on

查看:26
本文介绍了Android开机时启动后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要始终有一个后台服务来同步我的 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开机时启动后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆