Using Intent to send data

2019-03-03 19:17发布

问题:

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 to a textview.

回答1:

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