0

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!

Ian Panzica
  • 334
  • 1
  • 6
  • 20

3 Answers3

2

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);
    }



}
  • I'm trying something very similar to this that doesn't seem to be working but I'll look it over again and get back to you – Ian Panzica Oct 23 '14 at 06:17
  • I did this using this process for a big international pharmaceuticals company. And it works perfectly. Ok you are welcome. – Md. Shahadat Sarker Oct 23 '14 at 06:19
  • I noticed I didn't pass the handlers into the asynctask so that along with a couple other tweaks fixed my problem -> accepting this answer – Ian Panzica Oct 23 '14 at 18:31
1

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.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • Thanks a lot I'll look into this soon. I haven't read much about the LocalBroadcastManager it sounds pretty interesting. – Ian Panzica Oct 23 '14 at 06:18
1

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(...);
Andrew Luo
  • 919
  • 1
  • 5
  • 6
  • This has potential. My problem is that I'm trying to run a single asynctask that deals with periodically updating 2 (later more) separate fragments so I want to run it on its own and then be able to send messages from it to those fragments. – Ian Panzica Oct 23 '14 at 06:21
  • In that case you can use a Handler and post the chunks of work periodically to the UI thread. If you want to run the work in a separate thread, then just create the handler first on your ui thread (make it final, or declare it as a member of the activity), then create a new thread and pass the handler to it and use the handler's post to run code on the UI thread. – Andrew Luo Oct 23 '14 at 06:42