Sending data back to the Main Activity in Android

后端 未结 12 1922
后悔当初
后悔当初 2020-11-22 01:36

I have two activities: main activity and child activity.
When I press a button in the main activity, the child activity is launched.

Now I want to send some dat

12条回答
  •  爱一瞬间的悲伤
    2020-11-22 02:23

    All these answers are explaining the scenario of your second activity needs to be finish after sending the data.

    But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.

    In Second Activity -

    Intent intent = new Intent("data");
    intent.putExtra("some_data", true);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    

    In First Activity-

    private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // do some action
        }
    };
    

    Register the receiver in onCreate()-

     LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));
    

    Unregister it in onDestroy()

提交回复
热议问题