开发者

How to implement background tasks in Android

In my application I need, basically, two tasks performed in the background. One is sync some data with a php server, sending values and updating the local database with the answer periodically and the other is download files requested by the main thread from the server,notifying the UI when the download finish.

I only want do those things while the app is in foreground. And if the users opens another app, finish the current transactions and stop consuming resources.

At this point I'm a little lost about how to implement that. I have never 开发者_如何学编程used Services and I really dont know if a service is a valid solution, due to the service is used when you want your code still running when the app goes to background.

Other solution I've thought is to implement some kind of Handler that periodically (20 minutes for example) launches a thread for sync with the server. Lauching a thread also when a download is requested and sending a broadcast at the end.

What about that solution? Is valid? If yes, how can I detect when the app (not an activity) stops beeing at foreground in order to cancell the handler's posts?

Thanks in advance


If you choose the service I recommend you to use an IntentService http://developer.android.com/reference/android/app/IntentService.html

When you implement onHandleIntent you can have a loop that waits for the amount of time you want it to sleep, after it wakes up it can perform the task that you want.

@Override
protected void onHandleIntent(Intent intent) {
    while(true) {
        yourBackgroundTask();
        // Sleep
        try {
            wait(WAIT_TIME);
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
            break;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜