我正在开发一个应用程序,它拥有自己的数据库,并将通过GCM与后端同步,我正在考虑使用后台服务,但我不确定这是否是考虑它的正确方法所以,如果你能告诉我下面的内容是否正确,我真的很感激,如果没有,请你说出我需要做的步骤或者应该如何思考呢?不需要代码。
当应用程序没有正在运行/活动的活动时,假设GCM具有有效负载而无需联系后端,
1. Backend had new data and sent it with GCM
2. Background service received it and updated the DB
当应用程序当前正在运行时
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)
答案 0 :(得分:0)
总的来说,你的想法还可以。但您不需要始终运行后台Service
。只需创建WakefulBroadcastReceiver
并将其添加到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看起来像这样:
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)));
}
}
此接收器启动您的Service
(GCMService)。