Intent在实际开发中应用得比较广泛,除了用于开启启动activity和service,还可以用于除ContentProvider外的三大组件之间的数据传输,不仅作用于单个应用之内,还可以在多个应用之间进行通信(这种情况下一般使用隐式Intent,即通过Intent Filter进行匹配)
为了使版面整洁,就不粘贴xml布局文件(MainActivity有一个EditText和一个Button,ResultActivity有一个TextView)
1.显式Intent
Intent intent = new Intent(MainActivity.this,ResultActivity.class);
startActivity(intent);
2.隐式Intent
Intent intent = new Intent("wujiubuhuan");
startActivity(intent);
3.activity之间的数据传递,并且结合隐式Intent进行完整代码展示:
MainActivity代码:
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
private Button mButton;
private String className=getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.edittext);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取EditText框中的内容,并转化为String格式
String text = mEditText.getText().toString();
//判断EditText内是否为空字符串
if(text.isEmpty()){
Toast.makeText(MainActivity.this, "please type some character", Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(text);
//通过getPackageManager()获取PackageManager对象
PackageManager pm = getPackageManager();
//通过检测resolveInfo是否为null(text和ResultActivity的action匹配时,不为null),找到是否有component响应该Intent
ResolveInfo resolveInfo = pm.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY);
if(resolveInfo == null) {
Toast.makeText(MainActivity.this, "the wrong usage", Toast.LENGTH_SHORT).show();
} else{
i.putExtra("data", text);
startActivity(i);
}
}
}
});
}
}
ResultActivity代码:
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView mTextView = (TextView) findViewById(R.id.text);
Intent i = getIntent();
//由于Intent的数据底层使用Bundle包装,所以可以直接获取Bundle对象
Bundle b = i.getExtras();
String text = b.getString("data");
//另一种实现,通过Intent获取:String text = i.getStringExtra("data");
mTextView.setText(text);
}
}
Androidmanifest文件:
package="com.example.intentdemo">
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">