LunaVulpo
LunaVulpo

Reputation: 3211

How to update Activity from thread started in another activity?

I have a Main activity and after click on button I start thread (but the thread is hidden in library and I have only callback in Main activity. Now I want to start another activity (call A) where I want to put results from the thread. Below is simplified code:

public class Main extends Activity {


    XManager.ResultsCallback xResultsCallback = new XManager.ResultsCallback() {

// the method is called every 10 sec. 
        @Override
        public void onResult(ArrayList<String> texts) {


        }
    };

    XManager xManager = new xManager(xResultsCallback);
    View.OnClickListener onClick = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            XManager.start();

            Intent i = new Intent(Main.this, A.class);
            startActivity(i);

        }
    };


}

I want to update the content of A activity each time when onResult() method is called. How to do that?

Upvotes: 0

Views: 74

Answers (3)

pjq
pjq

Reputation: 1

I think if you want to decouple the logic, beside you can use the Android BroadcastReceiver, the another flexible choice is to use the Bus

And you can integrate it with gradle easily

dependencies {
  compile 'com.squareup:otto:+'
}

Upvotes: 0

Shubhang Malviya
Shubhang Malviya

Reputation: 1635

I have a suggestion that you should do as follows:

  1. Start Your Activity A on button click
  2. Inside Activity A declare your XManager instance with a callback present in A itself
  3. Then start your XManager as XManager.start(); that way you would be getting all the callbacks in your desired activity.

Have a great day!

Upvotes: 0

jazzyjester
jazzyjester

Reputation: 203

Use LocalBroadcastManager,

In your Main Activity create function :

private void sendResult() {
  Log.d("sender", "Broadcasting message");
  Intent intent = new Intent("custom-event-name");
  // You can also include some extra data.
  intent.putExtra("message", "This is my result!");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

and add BroadcastReceiver in your A Activity

private BroadcastReceiver onResult= new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("jazzy","onReceive called");

    }
};

add on OnCreate

@Override
public void onCreate(Bundle savedInstanceState) {

  // Register to receive messages.
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));
}

add onDestroy

@Override
protected void onDestroy() {
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

Upvotes: 2

Related Questions