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代码:
<pre>
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);
}
}
}
});
}
}
</pre>
ResultActivity代码:
<pre>
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);
}
}
</pre>
Androidmanifest文件:
<pre>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intentdemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".ResultActivity" >
<intent-filter>
<action android:name="wujiubuhuan" />
<!--必须有DEFAULT标签,startActivity会自动加上该选项,否则无法匹配-->
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
</pre>