Search code examples
androidandroid-activitycallback

implementing a callback in android with Activities


I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.

public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {        
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   } 
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI 
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}

Solution

  • I would do it like this :

    Create an interface :

    public interface MyReceiver {
      public void onReceive();
    }
    

    In you activity :

    public class MyActivity implements MyReceiver{
    
    public static MyReceiver myReceiver;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_new_booking);        
        super.onCreate(savedInstanceState);
        myReceiver = this;
        }
        
        @Override
        protected void onDestroy() {
            myReceiver = null;
        }
    
    
        @Override
        public void onReceive(){
           //Implement your code here or send objects in the parameters
        }
    
    }
    

    To Call it just use this:

    if(MyActivity.myReceiver!=null){
      MyActivity.myReceiver.onReceive();
    }
    

    No need to create activity instances.

    In this case i would also suggest you to use startActivityForResult.

    Hope this helps.