【问题标题】:Using Intent to send data使用 Intent 发送数据
【发布时间】:2012-02-09 21:57:46
【问题描述】:

如何在不离开活动 A 的情况下使用 Intent 从活动 A 向活动 B 发送数据(例如字符串)?我还需要知道如何捕获活动 B 中的数据并将其添加到文本视图中。

【问题讨论】:

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


【解决方案1】:

您正在寻找的是 Brodcast Reciver:

活动 A 应该发送广播:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多