Intent可以分為兩種:顯式Intent和隱式二蓝。
1.顯示Intent
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
2.使用隱式Intent
隱式Intent并不指明要啟動(dòng)那個(gè)活動(dòng),而是指定了一系列更為抽象的action洒缀,category等信息跷坝,然后交由系統(tǒng)去分析這個(gè)Intent倦蚪,并幫我們找到可以響應(yīng)這個(gè)隱式Intent的活動(dòng)去啟動(dòng)侣诵。
在AndroidManifest.xml中添加
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="android.intent.action.ACTION_START" />
<category android:name="android.intent.category.DEFULT" />
</intent-filter>
</activity>
Intent intent = new Intent(android.intent.action.ACTION_START);
startActivity(intent);
表示我們要啟動(dòng)能夠響應(yīng)android.intent.action.ACTION_START這個(gè)action的活動(dòng)痢法,因?yàn)閍ndroid.intent.category.DEFULT是一種默認(rèn)的category,在調(diào)用startActivity()方法的時(shí)候會(huì)自動(dòng)將這個(gè)category添加到Intent中杜顺。
那么如何添加categoty呢财搁?
只需intent.addCategory(android.intent.category.MY_CATEGORY);就行了。
當(dāng)然Intent的隱式調(diào)用不禁能打開同一個(gè)App里的活動(dòng)躬络,還能打開另一個(gè)App里的活動(dòng)尖奔,同樣只需要<action/>與new Intent();里的action相同即可,不過(guò)一般不建議這樣做洗鸵。
3.Intent的其他用法
-展示一個(gè)網(wǎng)頁(yè)
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
當(dāng)然越锈,要顯示出網(wǎng)頁(yè),要在AndroidManifest.xml中添加訪問(wèn)網(wǎng)絡(luò)的權(quán)限
<user-permission android:name="android.permission.INTERNET"/>
-調(diào)用系統(tǒng)撥號(hào)界面
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
3.向下個(gè)活動(dòng)傳遞數(shù)據(jù)
- 直接傳遞
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("data",content);
startActivity(intent);
接受數(shù)據(jù)
Intent intent = getIntent();
string content = intent.getStringExtar("data");
- 使用Bundle進(jìn)行傳遞
Bundle bundle = new Bundle();
bundle.put("key", value);
intent.putExtra(bundle);
intent.putExtra("key1",bundle);
接收數(shù)據(jù)
Intent intent = getIntent();
Bundle bundle = intent.getExtra();
bundle.getObject("key");
bundle.getObject("key1",value);//當(dāng)key1不存在是膘滨,value為默認(rèn)值
4.返回?cái)?shù)據(jù)給上一個(gè)活動(dòng)
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, requestCode);
在SecondActivity.java頁(yè)面放置要返回的數(shù)據(jù)
Intent intent = new Intent();
intent.putExtra("key", 1);
setResult("RESULT_OK", intent);
finish();
SecondActivity被銷毀后會(huì)回掉上個(gè)活動(dòng)的onActivityResult()方法。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case 1:
if (resultCode = RESULT_OK){
}
break;
}
}