Skip to content Skip to sidebar Skip to footer

Async Task Which Is Trigger In Different Class And Callback Function Is Implemented In Different Class

I am new to android and java. i have been doing a project in android studio in which i am using Asynctask to extract Location of user and there is a Call back interface to get Loca

Solution 1:

What is this LocationExtractor class ? For getting device current location and updates in location, have a look at https://developer.android.com/reference/android/location/LocationListener.html

Solution 2:

What you can do is create a Listener interface which will have one abstract method which the async class will called when the background task is completed.

publicinterfaceAsyncTaskCompletedListener{
    voidtaskCompleted();
}

In your asynctask you also have to register this Activity in order to get the callback. So the best way is to pass the activitie's context in the constructor of asynctask

Now implement this interface in the activities where you want this callback

classMyActivityimplementsAsyncTaskCompletedListener{
    //your code hereMyAsyncTasktask=newMyAsyncTask(this);

    @OverridevoidtaskCompleted(){
        //your code
    }
}

In your asynctask create a instance of AsyncTaskCompletedListener and assign it the value of passed context

MyAsyncTask extends AsyncTask<Void,Void,Void>{
     AsyncTaskCompletedListener listener;
     public MyAsyncTask(AsyncTaskCompletedListener listener){
          this.listener = listener;
     }

     @OverridepublicVoid onPostExecute(){
         this.listener.taskCompleted();
     }

}

Pass whatever data you want to pass to the taskCompleted method(You have to modify the interface accordingly). I just gave you a general method. Modify it as you want.

Post a Comment for "Async Task Which Is Trigger In Different Class And Callback Function Is Implemented In Different Class"