Android打开时启动后台服务

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

内容简介:翻译自: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打开时启动后台服务》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Rapid Web Applications with TurboGears

Rapid Web Applications with TurboGears

Mark Ramm、Kevin Dangoor、Gigi Sayfan / Prentice Hall PTR / 2006-11-07 / USD 44.99

"Dear PHP, It's over between us. You can keep the kitchen sink, but I want my MVC. With TurboGears, I was able to shed the most heinous FileMaker Pro legacy 'solu-tion' imaginable. It has relationshi......一起来看看 《Rapid Web Applications with TurboGears》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

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

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具