如何使用 Intent 将数据(例如字符串)从活动 A 发送到活动 B,而无需离开活动 A?我还需要知道如何捕获活动 B 中的数据并将其添加到文本视图中。
您正在寻找的是广播接收器:
我应该发送广播的活动:
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 http://developer.android.com/reference/android/content/BroadcastReceiver.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)