Background service in Android

给你一囗甜甜゛ 提交于 2019-12-11 19:27:22

问题


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)

回答1:


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).



来源:https://stackoverflow.com/questions/24098219/background-service-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!