Running activity in the background

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 04:34:30

问题


Just wondering if I could gather some constructive comments. Well, I am developing a tabbed application with activity group for each tab and related child activities. One of the activities handles a file downloader- waits for the download link from the server, once received download begins in the background. On completion, the file (mostly PDF) opens up in a generic viewer. This part works exceptionally well.

Now, coming to app requirement, I want the activity to run in background. When the user is in the download page, it shows a progress dialog with necessary messages. User, having decided to switch to other screens, moves to other screens. In real, the downloader activity should run in background.

A typical download activity class looks like:

 public class DownloadActivity extends Activity {
    public void onCreate(Bundle state) { //code here}
    public void onPause() {//can anything be done here?}
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
           //go back to previous screens to check other features
           TabGroupActivity parentActivity = (TabGroupActivity)getParent();
           //onBackPressed()- current activity is killed and new one is created
           parentActivity.onBackPressed();
           return true;
        }
        return super.onKeyUp(keyCode, event);
    }
 }

I want to modify the above activity to help it work background while user plays arounds with other screen.

Any thoughts?

Hope it is not very confusing! Let me know in case you don't understand any of the above.

Thanks in advance!


回答1:


Activity can't and shouldn't work in background. For background operations in Android you should use Service.

There is an article about Android processes and services.

Service doesn't have UI, it should do all the job, in the background. Activity can display current application state(s) to the user, that is changed/modified by Service. When Service finish his work, it could send a Notification, for example. More details in this guide.




回答2:


You can subclass AsyncTask (http://developer.android.com/reference/android/os/AsyncTask.html) through which you can do some work in background and post it to current activity through Handlers.



来源:https://stackoverflow.com/questions/12820346/running-activity-in-the-background

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