Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Relationship between Activity lifecycle and asynctask

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.11k
    Comment on it

    An Asynctask doesn't depend on Activity life-cycle that contains it. Like if we start an AsyncTask inside an Activity and then we rotates the device, the Activity will be destroyed at that point but the AsyncTask will remain same or not die until it completes.

    Then, when the AsyncTask complete its background work its directly updates Activity ui without creating new instance of activity or without affecting activity lifecycle.

    Theres also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

    For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-running background tasks, a different mechanism like service or intent service should be used.

    Example :

     private class AsyncTasks  extends AsyncTask<String, Void, JSONObject> {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
        }
    
        @Override
        protected JSONObject doInBackground(String... param) {
          //Perform some background opearations here
    
           jsonObject =  PostDataToUrl(url);
    
            return jsonObject;
        }
    
        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            super.onPostExecute(jsonObject);
    
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: