开发者

Android long update activity

开发者 https://www.devze.com 2023-04-03 11:02 出处:网络
I have a button in my app which leads to the UpdateActivity. This activity doesn\'t show anything just a progress bar and there is an AsyncTask running with the updates.

I have a button in my app which leads to the UpdateActivity. This activity doesn't show anything just a progress bar and there is an AsyncTask running with the updates.

The AsyncTask takes quite a long time because I conect to a server and retrieve info from many tables and inserting them in the sqlite database and sending data from local database to the server.

I am wondring if it's not better to use a service for this?? is it? On the other hand I have a doubt. When I press the back button I leave that activivty but the AsyncTask seems to be running in the back (because I have a toast to inform the user the job's done and it shows much later (even if I have left that activity!).

Then I have another activity which requires data to be read and written to/from the db so if I am doing that开发者_运维技巧 while another thread (the downloading thread) is messing up with the database too, is it possible that something goes wrong? Is there a way to prevent that? thanks in advance


Running your task in a service is defiantly a good idea for any long running operation that will outlive your Activity.

At the moment your thread continues to run after leaving the activity, but at any point that thread could be killed when the system kills the process.

Also presenting the user with UI from an Activity that has been and gone is not good for the UX.

The best thing to do is run your AsyncTask in a service and display status updates using a status bar notification. This way the user can get an update of the progress as and when they need to. A service with a status notification is seen as long running and the system won't kill the process (and therefore your thread) unless you are really low on memory.

As to the question of concurrent access to a database, you should probably write a ContentProvider to control access to your database. ContentProviders must be thread safe and will provide uniform access to your data within any part of your app and can even be used by other apps should you wish to export your data.


If you're concerned about the user making changes to the data while the sync is running, then making this a service won't really help you. What you can do is kill the AsyncTask (gracefully) in the Activities onDestroy() method, so that if a user clicks the back arrow, the task won't continue to run.

0

精彩评论

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