Android打开时启动后台服务

栏目: Android · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/11168869/starting-background-service-when-android-turns-on
我需要总是有一个后台服务来同步我的 Android

应用程序和服务器.我知道如何通过我的应用程序启动它,但是当Android关闭时,后台服务将会死亡.

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

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

使用<

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”/>用户出现或屏幕打开时启动服务.

翻译自:https://stackoverflow.com/questions/11168869/starting-background-service-when-android-turns-on


以上所述就是小编给大家介绍的《Android打开时启动后台服务》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Release It!

Release It!

Michael T. Nygard / Pragmatic Bookshelf / 2007-03-30 / USD 34.95

“Feature complete” is not the same as “production ready.” Whether it’s in Java, .NET, or Ruby on Rails, getting your application ready to ship is only half the battle. Did you design your system to......一起来看看 《Release It!》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具