使用Intent发送数据

时间:2012-02-09 21:57:46

标签: android android-layout android-intent android-activity textview

如何在不离开活动A的情况下使用意图将活动A中的字符串等数据发送到活动B?我还需要知道如何捕获活动B中的数据并将其添加到textview中。

1 个答案:

答案 0 :(得分:2)

您正在寻找的是Brodcast Reciver:

活动A应发送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应该实现接收器:

    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/reference/android/content/BroadcastReceiver.html