1

I have a common async task class that starts a tcp connection using my tcp client class. I am executing this async task while my main activity is launched and I define activity as caller. Here is my async class code:

public class CommonAsyncTask extends AsyncTask<Handler,String,String> {

    OnAsyncRequestComplete caller;
    Context context;
    String m;
    List<NameValuePair> parameters = null;
    ProgressDialog pDialog = null;
    public TCPClient client;

    public CommonAsyncTask(Activity a) {
        caller = (OnAsyncRequestComplete) a;
        context = a;
    }

    public interface OnAsyncRequestComplete {
        public void asyncResponse(String m);
    }

    @Override
    protected String doInBackground(Handler... params) {
        client = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            public void messageReceived(String message) {
                caller.asyncResponse(message);
            }
        });
        client.run();
        return null;
    }
}

When a message received I call caller.asyncResponse(message) and it runs in given activity. From main activity I start a new activity and I want to trigger caller.asyncResponse in this new activity and main activity simultaneously using the same async task class. If there are more then two activities I want to trigger that caller.asyncResponse in all activities. Is it possible to do this?

Blast
  • 955
  • 1
  • 17
  • 40

4 Answers4

0

If it needs to be received in all Activity's then you'd probably want to use a broadcast instead of a callback.

Android docs for BroadcastReceiver

And since you only want broadcasts within your app you'll also want to use it with the LocalBroadcastManager

This tutorial covers everything you'd need for this.

Sample Add a BroadcastReceiver to each Activity like so

BroadcastReceiver rec = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //all events will be received here
            //get message
            String message = intent.getStringExtra("message");
        }
    };
    LocalBroadcastManager.getInstance(this).registerReceiver(rec, new IntentFilter("event"));

To send a Broadcast. Instead of caller.asyncResponse(message);

  Intent intent = new Intent("event");
  // add data
  intent.putExtra("message", message);
  LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
triggs
  • 5,890
  • 3
  • 32
  • 31
  • I am really confused about broadcast. Is it possible to trigger a method in activity using broadcast or localbroadcastmagener when a message received? – Blast Jul 04 '14 at 12:38
  • Thank you so much but the `onReceive` method is not triggered in activity after `sendBroadcast(intetn)` ran. What is the reason? Should I add a permission in androidmanisfest.xml? – Blast Jul 04 '14 at 14:32
  • no permissions are needed, just that the receiver is registered to the manager and that the event names are the same – triggs Jul 04 '14 at 14:38
0

For some activitys, you can use Handlers. You need a handler by activity, then, you send a message to each handler and each activity will recive it.

MiguelAngel_LV
  • 1,200
  • 5
  • 16
0
public class Async_Task extends AsyncTask<Object, Void, String>
{

    byte[] fileInByte;
    int req_no;
    boolean morefiles = false;
    String TAG = "Async_Task";

    private HttpHelper parsing;
    private MultipartEntity multipart;
    private File currentFileuploading = null;
    private Validations valid;
    private Context context;
    private Object obj;
    private SharedPreferences pref;
    private InternetSchedul internetStatus;
    private AudioSchedul recordingSchedul;
    int uploadtype = 0;

    public Async_Task(int Req_no, Context mContext)
    {
        this.req_no = Req_no;
        multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        context = mContext;
        valid = new Validations(context);
        internetStatus = new InternetSchedul();
        recordingSchedul = new AudioSchedul();
    }

    public Async_Task(int Req_no, Context mContext, Object mObj)
    {
        this(Req_no, mContext);
        obj = mObj;
    }

    @Override
    protected void onPreExecute()
    {

    }

    @Override
    protected String doInBackground(Object... urls)
    {

        String obj = "";
        parsing = new HttpHelper();
        pref = context.getSharedPreferences(Constant.PREF_APPDATA, Context.MODE_PRIVATE);

        if (req_no == Constant.REQ_AUTHENTICATION)
        {


        }
        else if (req_no == Constant.REQ_UPLOAD)
        {


        }
        else if (req_no == Constant.REQ_FORCE_STOP)
        {


        }

        return "";

    }

    public byte[] getFile(String type)
    {

        //return file in byte
    }

    @Override
    protected void onPostExecute(String result)
    {

                if (obj instanceof GCMIntentService)
                {
                    ((GCMIntentService) obj).getApiResponse(req_no);
                }
                else if (obj instanceof Internet_SD_CheckService)
                {

                }
                else if (obj instanceof Activity_Audio)
                {
                    ((Activity_Audio) obj).getApiResponse(req_no, result);
                }


    }
}

Calling

if(valid.isOnline())
            new Async_Task(Constant.REQ_AUTHENTICATION, Activity_Audio.this, Activity_Audio.this).execute();

Or try below link if you want more functionality.

http://www.technotalkative.com/android-volley-library-example/

Bhavesh Jethani
  • 3,891
  • 4
  • 24
  • 42
0

You should create a new AsyncTask for each call.

See the docs of AsyncTask,

Threading rules

  • The goal of the AsyncTask is to take care of thread management for you and you should not worry about the threading mechanisms.

  • The Android Platform handles the pool of threads to manage the asynchronous operations. AsyncTasks are like consumables. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Source: should-you-create-new-async-tasks-for-every-different-call-or-use-the-same-one

Community
  • 1
  • 1
sjain
  • 23,126
  • 28
  • 107
  • 185