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