闡述Android Intent使用整理問題
在進行對Android Intent匹配的前提是要匹配Intent的幾項值:Action, Category, Data/Type,Component如果填寫了Componet就是上例中的Test.class)這就形成了顯示匹配,匹配規(guī)則為最大匹配規(guī)則。
1,如果你填寫了Action,如果有一個程序的Manifest.xml中的某一個Activity的IntentFilter段中定義了包含了相同的Action那么這個Intent就與這個目標Action匹配。如果這個Filter段中沒有定義Type,Category,那么這個Activity就匹配了。但是如果手機中有兩個以上的程序匹配,那么就會彈出一個對話可框來提示說明。#t#
Action的值在Android中有很多預定義,如果你想直接轉(zhuǎn)到你自己定義的Intent接收者,你可以在接收者的Android Intentr中加入一個自定義的Action值(同時要設(shè)定Category值為"android.intent.category.DEFAULT")。在你的Android Intent中設(shè)定該值為Intent的Action,就直接能跳轉(zhuǎn)到你自己的Intent接收者中。因為這個Action在系統(tǒng)中是唯一的。
2,data/type,你可以用Uri來做為data,比如Uri uri = Uri.parse(http://www.google.com);Intent i = new Intent(Intent.ACTION_VIEW,uri);手機的Intent分發(fā)過程中,會根據(jù)http://www.google.com 的scheme判斷出數(shù)據(jù)類型type。手機的Brower則能匹配它,在Brower的Manifest.xml中的IntenFilter中首先有ACTION_VIEW Action,也能處理http:的type。
3,至于分類Category,一般不要去在Intent中設(shè)置它,如果你寫Intent的接收者,就在Manifest.xml的Activity的IntentFilter中包含android.category.DEFAULT,這樣所有不設(shè)置Category(Intent.addCategory(String c);)的Intent都會與這個Category匹配。
4,extras(附加信息),是其它所有附加信息的集合。使用extras可以為組件提供擴展信息,比如,如果要執(zhí)行“發(fā)送電子郵件”這個動作,可以將電子郵件的標題、正文等保存在extras里,傳給電子郵件發(fā)送組件。
例子代碼:
- public class HelloActivity extends Activity {
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // TODO Auto-generated method stub
- super.onCreateOptionsMenu(menu);
- menu.add(0, Menu.FIRST+1, 1, R.string.menu_open);
- menu.add(0, Menu.FIRST+2, 2, R.string.menu_edit);
- menu.add(0, Menu.FIRST+3, 3, R.string.menu_update);
- menu.add(0, Menu.FIRST+4, 4, R.string.menu_close);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // TODO Auto-generated method stub
- super.onOptionsItemSelected(item);
- switch(item.getItemId())
- {
- case Menu.FIRST + 1:
- {
- this.setTitle("Open Text!");
- Intent i = new Intent();
- i.setAction("test_action");
- if (Tools.isIntentAvailable(this,i))
- this.startActivity(i);
- else
- this.setTitle("the Intent is unavailable!!!");
- break;
- }
- case Menu.FIRST + 2:
- {
- this.setTitle("Edit Text!");
- break;
- }
- case Menu.FIRST + 3:
- {
- this.setTitle("Update Text!");
- break;
- }
- case Menu.FIRST + 4:
- {
- this.setTitle("Close Text!");
- break;
- }
- }
- return true;
- }