Intent意为:意图。简单的理解就是用来从一个Activity/Service跳转到另一个Activity/Service中,并可以携带数据,也可以在这个程序调用别的程序。这样我们虽然不懂如何结息条形码,却可以通过开放的android平台,在我们的程序调用专家写好的程序来实现功能。
Intent的用法:
(1)从MainActivity跳转到NewActivity
Intent intent=new Intent(MainActivity,this,NewActivity.this);
startAcitivity(intent);
(2)从MainActivity跳转到NewActivity,并携带数据
有两种写法,本质上并无很大区别
Intent intent=new Intent(MainActivity,this,NewActivity.this);
Bundle bundle=new Bundle();
bundle.putString("name", "value");
intent.putExtras(bundle);
startAcitivity(intent);
接收
mintent=this.getIntent();
bundle=mintent.getExtras();
String a=bundle.getString("name");
---------------------------------------------------------------------------------
Intent intent=new Intent(MainActivity,this,NewActivity.this);
intent.putExtra("name","value");
startAcitivity(intent);
接收
String a=mintent.getStringExtra("name");
第一种方法当bundle的值要传给多个activity时较为简便。
(3)从MainActivity跳转到NewActivity,并携带数据,并且要从NewActivity跳转回MainActivity且携带数据。
Intent intent=new Intent(MainActivity.this,NewActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name","value");
intent.putExtras(bundle);
startActivityForResult(intent,1234);
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
if (resultCode==4321)
{
String a=data.getStringExtra("name");
Toast.makeText(this, a, Toast.LENGTH_LONG).show();;
}
super.onActivityResult(requestCode, resultCode, data);
}
//请求码requestCode=1234
mintent.putExtra("name", "你好");
setResult(4321, mintent);
finish();
//结果码result=4321
//程序例子A调用程序例子B
intent.setClassName("com.example.lizib", "com.example.lizib.MainActivity");
Bundle bundle=new Bundle();
bundle.putString("STR_INPUT", "HI,我来自例子A...");
intent.putExtras(bundle);
startActivityForResult(intent, 1234);
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
if (resultCode!=RESULT_OK)
{
return;
}
else
{
String aaa=data.getStringExtra("STR_BACK");
tv.setText("来自例子B:"+aaa);
}
super.onActivityResult(requestCode, resultCode, data);
}
//接收
Bundle bundle=getIntent().getExtras();
strRet=bundle.getString("STR_INPUT");
//返回
Bundle bundle=new Bundle();
bundle.putString("STR_BACK", "我是例子B");
Intent intent=new Intent();
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
finish();