Using Intent to send data

后端 未结 1 1104
鱼传尺愫
鱼传尺愫 2021-01-28 23:10

How can i use intent to send data such as a string from activity A to activity B without leaving activity A? I also need to know how to capture the data in activity B and add it

1条回答
  •  鱼传尺愫
    2021-01-28 23:17

    what you are looking for is Brodcast Reciver:

    activity A should send brodcast:

    public class ActivityA extends Activity
    {
         private void sendStringToActivityB()
         {
             //Make sure to have started ActivityB first, otherwise B wont be listening on the receiver:
             startActivity(ActivityA.this, ActivityB.class);
             //Then send the data
             Intent intent = new Intent("someIntentFilterName");
             intent.putExtra("someKeyName", "someValue");
             sendBroadcast(intent);
         }
    }
    

    and activity B should implement receiver:

        public class ActivityB extends Activity
        {
            private TextView mTextView;
    
            private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()
            {       
                @Override
                public void onReceive(Context context, Intent intent)
                {
                    String strValueRecived = intent.getStringExtra("someKeyName","defaultValue");
                    mTextView.setText(strValueRecived);
                }
             };
    
             @Override
             protected void onCreate(Bundle savedInstanceState)
             {
                  super.onCreate(savedInstanceState);
                  mTextView = (TextView)findViewById(R.id.textView); 
    
    
                  registerReceiver(mBroadcastReceiver, new IntentFilter("someIntentFilterName"));
             } 
    } 
    

    the example not complete, but you can read about it on the link: http://developer.android.com/reference/android/content/BroadcastReceiver.html

    0 讨论(0)
提交回复
热议问题