在Android的后台服务 [英] Background service in Android

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

问题描述

我工作的一个应用程序,其中它有它的自己的数据库,并通过GCM后端进行同步,我想使用后台服务的,但我不知道这是考虑它的正确方法,所以,我真的AP preciate如果你能告诉我下面的正确与否,如果不是你能请注明我需要什么步骤做或应该如何看待呢?没有code是必需的。

当应用程序没有运行/活泼的活动,认为GCM有一个有效载荷,无需接触后端,

  1。后端有新的数据和GCM寄给
2.背景服务接收并更新数据库

当应用程序正在运行

  1。后端有新的数据和GCM寄给
2.背景服务接收并更新数据库,并notifydatasetchanged
作为源已经改变3.活动数据将被改变(例如列表视图更新的项目)


解决方案

在一般你的想法是好的。但你并不需要始终在后台运行服务。只要创建 WakefulBroadcastReceiver ,并将其添加到您的清单

 <接收
        机器人:名字=。receivers.GCMReceiver
        机器人:权限=com.google.android.c2dm.permission.SEND>    &所述;意图滤光器>
        <作用机器人:名字=com.google.android.c2dm.intent.RECEIVE/>
        <类机器人:名字=com.your.package/>
    &所述; /意图滤光器>
< /接收器>

接收器可以是这样的:

 公共类GCMReceiver扩展WakefulBroadcastReceiver {
    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        组件名排版=新单元名(context.getPackageName(),GCMService.class.getName());
        startWakefulService(上下文,(intent.setComponent(化合物)));
    }
}

该接收器启动您的服务(GCMService)。

I'm working on an app where it has it's own DB and will be syncing with the backend via GCM, I'm thinking of using background service but I'm not sure if this is the right way to think about it, so, I would really appreciate if you can tell me the below is correct or not, if not can you please state what I need to do in steps or how should think about it? no code is required.

When the app has no running/active activity, assume that GCM has a payload and no need to contact the backend,

1. Backend had new data and sent it with GCM 
2. Background service received it and updated the DB

When the app is currently running

1. Backend had new data and sent it with GCM 
2. Background service received it and updated the DB and notifydatasetchanged
3. Data on activity will be changed as the source has changed(e.g listview update it's items)

解决方案

In general your idea is ok. But you don't need to have always running background Service. Just create WakefulBroadcastReceiver and add it into your Manifest:

<receiver
        android:name=".receivers.GCMReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">

    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.your.package" />
    </intent-filter>
</receiver>

Receiver could look like this:

public class GCMReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(), GCMService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
    }
}

This receiver launches your Service(GCMService).

这篇关于在Android的后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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