使用意图发送数据

问题描述:

我如何使用意图发送数据如字符串从活动A到b活动不留活性的?我还需要知道如何捕捉数据b活动并将其添加到一个TextView。

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.

您正在寻找的是Brodcast Reciver:

what you are looking for is Brodcast Reciver:

活性的应该发送brodcast:

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);
     }
}

和b活动应该实现接收器:

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"));
         } 
} 

示例中未完成,但 你可以读到它的链接: http://developer.android.com/参考/安卓/内容/ BroadcastReceiver.html

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