Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android make callback to an Activity from java class

How can i make a callback to an Activity form a Java Class?

Example:

    public class TestClass{
    String text = "Test";
    public TestClass(Context context){
            startActivity(new Intent(context, SomeActivity.class));
    }

    private void sendToSomeActivity(){
      //Call some method of SomeActivity and pas text as string
    }

   }

When sendToSomeActivity() is called, i want to make a callback to the already started SomeActivity and pass some text to the Activity. In SomeActivity i want to use the text.

Note: The TestClass object that i want to use is already created in another class.

How can this be done?

like image 897
user3494179 Avatar asked Mar 25 '15 13:03

user3494179


1 Answers

The solution I chose is as follows:

Use BroadcastReceivers to communicate between Java classes and Activities.

Example:

public class SomeActivity extends Activity{
    private MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        receiver = new MyBroadcastReceiver();
        this.registerReceiver(receiver, new IntentFilter(MyBroadcastReceiver.ACTION));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(receiver);
    }

    private class MyBroadcastReceiver extends BroadcastReceiver{
        public static final String ACTION = "com.example.ACTION_SOMETHING"
        @Override
        public void onReceive(Context context, Intent intent) {
            String test = intent.getStringExtra("dataToPass");
        }
    }
} 

public class TestClass{
    private String test = "TEST";
    private Context context;

    public TestClass(Context context){
      this.context = context;
    }
    private void sendToSomeActivity(){
       Intent intent = new Intent();
       intent.setAction(SomeActivity.MyBroadcastReceiver.ACTION);
       intent.putExtra("dataToPass", test);
       context.sendBroadcast(intent); 
    }

}
like image 163
user3494179 Avatar answered Sep 27 '22 18:09

user3494179