Ian Panzica
Ian Panzica

Reputation: 354

Get message to fragment from AsyncTask

Let me start by apologizing I don't have much code to show. Here's the situation: I'm trying to run a periodic update in the background using an AsyncTask. This particular async task is NOT defined in an activity or anything but instead in its own class. I was wondering if there was a way for me to send a message from this task in the doInBackground() method to somewhere else, for example, to a fragment somewhere else in the code (really anywhere at this point). I've looked into using .post() and am currently trying to use a Handler to send and receive messages with no luck. Thanks in advance!

Upvotes: 0

Views: 847

Answers (3)

Andrew Luo
Andrew Luo

Reputation: 927

in the doInBackground method, return the message that you want to send, then in the activity or frag that you instantiated the asynctask, override the onPostExecute to process the message, for example if the message is an Int code:

class MyTask extends AsyncTask<...,...,Int> {
    protected Int doInBackground(.....

....
}

In activity:

new MyTask() {
    protected void onPostExecute(Int code) {
       //do some processing of code here.
    }
}.execute(...);

Upvotes: 1

Md. Shahadat Sarker
Md. Shahadat Sarker

Reputation: 849

Call AsycTask with hanlder in fragment or anywhere:

new DoctorCallReportTask(context,handler, taskData).execute();

Your Handler in fragment or anywhere:

Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        String messages = (String) msg.getData().getSerializable("data");

        Toast.makeText(Context,  messages, Toast.LENGTH_LONG).show();

    }
};

Your AsycTask - separate file class;

import java.util.ArrayList;

import net.iecl.sinorise.R;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DoctorCallReportTask extends AsyncTask<Void, Integer, Void> {
    private Context context;
    private Handler handler;
    private ProgressDialog dialog;
    String data="";

    public DoctorCallReportTask(Context context,Handler handler,String data) {
        this.context = context;
        this.handler = handler;
        this.data=data;
        dialog = new ProgressDialog(context);
    }



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
         this.dialog.setMessage("Resolving Doctor Call Report...");
         this.dialog.show();


    }

    @Override
    protected Void doInBackground(Void... params) {
        result= "You task result return here";
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
         if (dialog.isShowing()) {
                dialog.dismiss();
         }
        Message msg = Message.obtain();
        Bundle b = new Bundle();
        b.putSerializable("data", this.result);
        msg.setData(b);
        handler.sendMessage(msg);
    }



}

Upvotes: 2

Shobhit Puri
Shobhit Puri

Reputation: 26007

If you want to regularly send updates to UI thread, use onProgressUpdate function of AsyncTask. If you want to send a message after doInBackground finishes, then use onPostExecute function of AsyncTask. Now if from any of those functions you want to send a message to some other Activity/Fragment, you can use LocalBroadcastManager.

You will have to register the receiver in all those receiving activities. The Sender sends/broadcasts notifications and the receiver activity/Fragment watches for notifications. Receiver has to register the Broadcast Receiver for receiving the notifications. As per the docs:

It is a helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent). One of them is that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.

For seeing how you can implement it you can see how to use LocalBroadcastManager? .

That's my 2 cents.

Upvotes: 1

Related Questions