简体   繁体   中英

How do you call web service in android such that it will continue waiting for response even when activity is on background?

What approach do I have to take if I need to connect to a web service and make sure it will continue downloading even after the screen has been rotated or a phone call suddenly pops up or the activity has been put on the background?

I've read from some of the answers here that it is either you use AsyncTask or a Service to connect to the web service. Is it really the proper approach when connecting to web service? What is the more suggested approach and the commonly used approach? I'll appreciate it if you could also give me some explanation and sample codes regarding the approach that you will be suggesting.

It really depends on your requirements:

Service
If your request is taking a long time to finish and your application is heavily depending on the result (persistent data) I would suggest to use a service because the android system can decide to kill an application which was pushed to the background and your request will be simply gone.

AsyncTask
For small requests with data which your application is only needing for a current state (data which can pe thrown away after real application close) I would use a AsyncTask. This could get really tricky to handle when orientation changes occur so I provide an example ( note - it's a blueprint to get the idea, not a final solution).

When is my Application and my AsyncTask getting killed?
When you push your application to the background it will be still active. If you use antoher application and this request more memory, the android system can dicide to kill your active application to free needed resources. From this moment your activity and your task is gone. But there is still a chance for the task to finish and persit it's results in a database or on the SD card.

public class YourActivity extends Activity {

    private MyReqeustTask mRequestTask;

    public void onCreate(Bundle state) {
         // your activity setup

         // get your running task after orientation change
         mRequestTask = (MyRequestTask) getLastNonConfigurationInstance();

         if (mRequestTask != null) {
             mRequestTask.mActivity = new WeakReference<MyActivity>(this);
             processRequest();
         }
    }

    // call that somewhere - decide what implementation pattern you choose
    // if you need more than a single request - be inventive ;-)
    public startRequest() {
        mRequestTask = new MyRequestTask();
        mRequestTask.mActivity = new WeakReference<MyActivity>(this);
        mRequestTaks.execute(your, params);
    }

    // this is a request to process the result form your actual request
    // if it's still running, nothing happens
    public processResult() {
        if (mRequestTask == null || mRequest.getStatus() != Status.FINISHED) {
            return;
        }

        Result result = mRequest.getResult();
        // update and set whatever you want here
        mRequestTask = null;
    }

    public Object onRetainNonConfigurationInstance() {
        // retain task to get it back after orientation change
        return mRequestTask;
    }

    private static MyRequestTaks extends AsyncTask<Params, Progress, Result> {

        WeakReference<MyActivity> mActivity;

        protected Result doInBackground(Params... params) {
            // do your request here
            // don't ever youe mActivity in here, publish updates instead!
            // return your final result at the end
        }

        protected void onProgressUpdate(Progress... progress) {
            MyActivity activity = mActivity.get();

            if (activity != null) {
                // do whatever your want to inform activity about undates
            }
        }

        protected void onPostExecute(Result result) {
            MyActivity activity = mActivity.get();

            if (activity != null) {
                // this will update your activity even if it is paused
                activity.processRequest();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM