Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

intentservice - Background service in Android

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...