Intent的基本使用
本節引言:
在上一節結束後意味著Android的四大組件我們都已經學習完畢了~,而本節我們要學習的是四大組件間的 樞紐-Intent(意圖),Android通訊的橋樑,例如我們可以透過:
- #startActivity(Intent)/startActivityForResult(Intent ):來啟動一個Activity
- startService(Intent)/bindService(Intent):來啟動一個Service
- sendBroadcast:發送廣播到指定BroadcastReceiver
- 另外別忘了我們在註冊四大元件時,寫得很多的Intent-Filter哦~
好吧,話不多說,開始本節內容!另外前面我們已經用過Intent了,就不在講述概念性的東西了~ 舊規矩,官方API:Intent
1.顯式Intent與隱式Intent的區別
- ##顯式Intent:透過元件名稱指定啟動的目標元件,例如startActivity(new Intent(A.this,B.class)); 每次啟動的元件只有一個~
- 隱含明確Intent:不指定元件名,而指定Intent的Action,Data,或Category,當我們啟動元件時, 會去匹配AndroidManifest.xml相關元件的Intent-filter,逐一匹配出滿足屬性的元件,當不只一個滿足時, 會跳出一個讓我們選擇啟動哪一個的對話框~
2.Intent的七個屬性:
1)ComponentName(元件名稱)
2)Action(動作)
3)Category(類別)
4)Data(資料),Type(MIME類型)
5)Extras (額外)
6)Flags(標記)
3.明確Intent使用範例:這個用得很多,直接就上例子了:
範例1:點選按鈕返回Home介面:運行效果圖:
#核心程式碼:
Intent it = new Intent();
it.setAction(Intent.ACTION_MAIN);
it.addCategory(Intent.CATEGORY_HOME);
startActivity(it);
it.setAction(Intent.ACTION_MAIN);
it.addCategory(Intent.CATEGORY_HOME);
startActivity(it);
範例2:點選按鈕開啟百度頁面:執行效果圖:
核心程式碼:
Intent it = new Intent();
it.setAction(Intent.ACTION_VIEW);
it.setData(Uri.parse( "http://www.baidu.com"));
startActivity(it);
it.setAction(Intent.ACTION_VIEW);
it.setData(Uri.parse( "http://www.baidu.com"));
startActivity(it);
#4.隱含Intent詳解
1)預先定義動作的隱式Intent範例:
程式碼範例:點選按鈕後,所有Action為VIEW的Activity被篩選出來,由用戶進一步選擇:
核心程式碼:
建立第二個Activity的佈局,與對應的Activity,在第一個Activity的按鈕點擊事件中加入程式碼:
Intent it = new Intent();
it.setAction(Intent.ACTION_VIEW);
startActivity(it);
it.setAction(Intent.ACTION_VIEW);
startActivity(it);
最後在第二個Activity的Intent中加入以下程式碼:
<activity android:name=".SecondActivity"
android:label="第二個Activity"> intent-filter>
<action android:name="android.intent.action.VIEW"/>
<categoryandroidd# <categoryandroidandroidname="android.int # </intent-filter>
</activity>
android:label="第二個Activity"> intent-filter>
<action android:name="android.intent.action.VIEW"/>
<categoryandroidd# <categoryandroidandroidname="android.int # </intent-filter>
</activity>
2)自訂動作的隱含Intent範例:
程式碼範例:使用自訂的Action與category來啟動另一個Activity
核心程式碼:
建立第二個Activity的佈局,與對應的Activity,在第一個Activity的按鈕點擊事件中加入程式碼:
Intent it = new Intent();it.setAction("my_action");
it.addCategory("my_category");startActivity(it);
最後在第二個Activity的Intent中加入以下程式碼:
<activity android:name=".SecondActivity"
android:label="第二個Activity"> ;
<intent-filter>
<action android:name="my_action"/>
<category android: name="android.intent.category.DEFAULT"/>
</intent-filter>
<ego/activity>
Im#>#>如果我們注意#catrym;/activity>
#>>我們雖然我們注意#catrym;但還是要把這個預設的加上,不然會報錯的:android:label="第二個Activity"> ;
<intent-filter>
<action android:name="my_action"/>
<category android: name="android.intent.category.DEFAULT"/>
</intent-filter>
<ego/activity>
Im#>#>如果我們注意#catrym;/activity>
5.常用系統Intent集合
大家貼下常用的系統Intent的集合吧,上面沒有的歡迎提出~
//============================================ =====================
//1.撥打電話
// 給行動客服10086撥打電話
Uri uri = Uri.parse ("tel:10086");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
//========== ==================================================== ===
//2.發送簡訊
// 寄給10086發送內容為「Hello」的簡訊
Uri uri = Uri.parse("smsto:10086");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello");
startActivity(intent);
#//3.寄送彩信(相當於傳送附附件的簡訊)
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", "Hello");
Uri uri = Uri.parse("content ://media/external/images/media/23");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/png");
startActivity(intent) ;
//=========================================== ======================
//4.打開瀏覽器:
// 打開百度主頁
Uri uri = Uri.parse("http://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//= ==================================================== ============
//5.發送電子郵件:(閹割了Google服務的沒戲!!!!)
// 給someone@domain.com發郵件
Uri uri = Uri.parse("mailto:someone@domain.com");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(intent);##/# / 寄給someone@domain.com寄電子郵件寄件內容為「Hello」的郵件
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "someone@domain.com") ;
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.setType("text/plain");
startActivity(intent);
// 寄email
Intent intent=new Intent(Intent.ACTION_SEND);
String[] tos = {"1@abc.com", "2@abc .com"}; // 收件人
String[] ccs = {"3@abc.com", "4@abc.com"}; // 抄送
String[] bccs = {" 5@abc.com", "6@abc.com"}; // 密送
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_BCC, bccs);
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");##intent.putExtra(Intent.EXTRA_TEXT, "Hello");
##intent.setType("message/rfc822");
startActivity(intent);
//======================= ========================================
//6.顯示地圖:
// 打開Google地圖中國北京位置(北緯39.9,東經116.3)
Uri uri = Uri.parse("geo:39.9,116.3");
Intent intentent .ACTION_VIEW, uri);
startActivity(intent);
//============================== ===================================
//7.路徑規劃
// 路徑規劃:北京某地(北緯39.9,東經116.3)到上海某地(北緯31.2,東經121.4)
Uri uri = Uri.parse("http://maps.google.com/maps? f=d&saddr=39.9 116.3&daddr=31.2 121.4");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);##==#startActivity(intent);
#/VIEW, uri);##==#startActivity(intent);
#////== ==================================================== ========
//8.多媒體播放:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:// /sdcard/foo.mp3");
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
//取得SD卡下所有音訊檔案,然後播放第一首=-=
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent intent new遠o? (intent);
//====================================== =========================
//9.打開相機拍照:
// 開啟拍照程式
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
// 取出照片資料
Bundle extras =it extras.get("data");
//另一種:
//調用系統相機應用程序,並儲存拍攝下來的照片
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
time = Calendar.getInstance().getTimeInMillis();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
.getExternalStorageDisoltory). tucue", time + ".jpg")));
startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE);
#//=================== ============================================
//10.取得並剪下圖片
// 取得並剪下圖片
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true"); // 開啟剪下
intent.putExtra("aspectX", 1); // 剪切的寬高比為1:2
intent.putExtra ("aspectY", 2);
intent.putExtra("outputX", 20); // 保存圖片的寬度和高度
intent.putExtra("outputY", 40);
intent.putExtra("output", Uri.fromFile(new File ("/mnt/sdcard/temp"))); // 保存路徑
intent.putExtra("outputFormat", "JPEG");// 回傳格式
startActivityForResult(intent, 0);
# // 剪下特定圖片
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera. CropImage");
intent.setData(Uri.fromFile(new File("/mnt/sdcard/temp")));
intent.putExtra("outputX", 1); // 剪下的寬度高比為1:2
intent.putExtra("outputY", 2);
intent.putExtra("aspectX", 20); // 保存圖片的寬度與高
intent.putExtra(" aspectY", 40);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.parse(" file:///mnt/sdcard/temp"));
startActivityForResult(intent, 0);
//================== ===============================================
//11.打開Google Market
// 打開Google Market直接進入程式的詳細頁面
Uri uri = Uri.parse("market://details?id=" + "com.demo.app ");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
##//=============== ================================================
##//12.進入手機設定介面:
// 進入無線網路設定介面(其它可舉一反三)
Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); (intent, 0);
//==================================== ===========================
//13.安裝apk:
Uri installUri = Uri.fromParts( "package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
#//================ =================================================
//14.卸載apk:
Uri uri = Uri.fromParts("package", strPackageName, null);
約庫) it);
//========================================= ========================
//15.發送附件:
Intent it = new Intent(Intent.ACTION_SEND) ;
###################################################################1正it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///cardcard/eoe.mp3"); /mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//==================== ===============================================
//16.進入聯絡人頁面:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(People.CONTENT_URI);
intent);
//======================================= ========================
//17.查看指定聯絡人:
Uri personUri = ContentUris. withAppendedId(People.CONTENT_URI, info.id);//info.id聯絡人ID
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(personUri );
startActivity(intent);
//================================== ===============================
//18.呼叫系統編輯新增聯絡人(高版本SDK有效):
Intent it = newIntent(Intent.ACTION_INSERT_OR_EDIT);
it.setType("vnd.android.cursor.item/contact"); ;
it.putExtra("name","myName");
it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY, "organization"); provider.Contacts.Intents.Insert.EMAIL,"email");
it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone"); Contacts.Intents.Insert.SECONDARY_PHONE,"mobilePhone");
it.putExtra( android.provider.Contacts.Intents.Insert.TERTIARY_PHONE,"workPhone"); Intents.Insert.JOB_TITLE,"title");
startActivity(it);
//========================= ========================================
//19.呼叫系統編輯新增聯絡人(全有效):
Intent intent = newIntent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(People.CONTENT_ITEM_TYPE); , "My Name");
#intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");
intent.putExtra(Contacts.Intoness.Inert
Intent.putExtra(Contacts.Intents.Insert.EMAIL,“com@com.com”);
intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, Contacts.ContactMethodsColumns.TYPE_WORK);
startActivity(意圖);
//================================== == =============================
//20.開啟另一個程式
Intent i = new意圖();
ComponentName cn = new ComponentName("com.example.jay.test",
"com.example.jay.test.MainActivity");
i.setComponent(cn);
i.setAction("android.intent.action.MAIN");
startActivityForResult(i, RESULT_OK);
//================================ == ===============================
//21.開啟錄音機
Intent mi = new意圖(Media.RECORD_SOUND_ACTION);
startActivity(mi);
//================================== == =============================
//22.來自google內容搜尋
意圖意圖=新意圖();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);
//===================== == =============================================
//1.撥打電話
// 給行動客服10086撥打電話
Uri uri = Uri.parse ("tel:10086");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
//========== ==================================================== ===
//2.發送簡訊
// 寄給10086發送內容為「Hello」的簡訊
Uri uri = Uri.parse("smsto:10086");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello");
startActivity(intent);
#//3.寄送彩信(相當於傳送附附件的簡訊)
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", "Hello");
Uri uri = Uri.parse("content ://media/external/images/media/23");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/png");
startActivity(intent) ;
//=========================================== ======================
//4.打開瀏覽器:
// 打開百度主頁
Uri uri = Uri.parse("http://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//= ==================================================== ============
//5.發送電子郵件:(閹割了Google服務的沒戲!!!!)
// 給someone@domain.com發郵件
Uri uri = Uri.parse("mailto:someone@domain.com");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(intent);##/# / 寄給someone@domain.com寄電子郵件寄件內容為「Hello」的郵件
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "someone@domain.com") ;
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.setType("text/plain");
startActivity(intent);
// 寄email
Intent intent=new Intent(Intent.ACTION_SEND);
String[] tos = {"1@abc.com", "2@abc .com"}; // 收件人
String[] ccs = {"3@abc.com", "4@abc.com"}; // 抄送
String[] bccs = {" 5@abc.com", "6@abc.com"}; // 密送
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_BCC, bccs);
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");##intent.putExtra(Intent.EXTRA_TEXT, "Hello");
##intent.setType("message/rfc822");
startActivity(intent);
//======================= ========================================
//6.顯示地圖:
// 打開Google地圖中國北京位置(北緯39.9,東經116.3)
Uri uri = Uri.parse("geo:39.9,116.3");
Intent intentent .ACTION_VIEW, uri);
startActivity(intent);
//============================== ===================================
//7.路徑規劃
// 路徑規劃:北京某地(北緯39.9,東經116.3)到上海某地(北緯31.2,東經121.4)
Uri uri = Uri.parse("http://maps.google.com/maps? f=d&saddr=39.9 116.3&daddr=31.2 121.4");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);##==#startActivity(intent);
#/VIEW, uri);##==#startActivity(intent);
#////== ==================================================== ========
//8.多媒體播放:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:// /sdcard/foo.mp3");
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
//取得SD卡下所有音訊檔案,然後播放第一首=-=
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent intent new遠o? (intent);
//====================================== =========================
//9.打開相機拍照:
// 開啟拍照程式
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
// 取出照片資料
Bundle extras =it extras.get("data");
//另一種:
//調用系統相機應用程序,並儲存拍攝下來的照片
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
time = Calendar.getInstance().getTimeInMillis();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
.getExternalStorageDisoltory). tucue", time + ".jpg")));
startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE);
#//=================== ============================================
//10.取得並剪下圖片
// 取得並剪下圖片
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true"); // 開啟剪下
intent.putExtra("aspectX", 1); // 剪切的寬高比為1:2
intent.putExtra ("aspectY", 2);
intent.putExtra("outputX", 20); // 保存圖片的寬度和高度
intent.putExtra("outputY", 40);
intent.putExtra("output", Uri.fromFile(new File ("/mnt/sdcard/temp"))); // 保存路徑
intent.putExtra("outputFormat", "JPEG");// 回傳格式
startActivityForResult(intent, 0);
# // 剪下特定圖片
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera. CropImage");
intent.setData(Uri.fromFile(new File("/mnt/sdcard/temp")));
intent.putExtra("outputX", 1); // 剪下的寬度高比為1:2
intent.putExtra("outputY", 2);
intent.putExtra("aspectX", 20); // 保存圖片的寬度與高
intent.putExtra(" aspectY", 40);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.parse(" file:///mnt/sdcard/temp"));
startActivityForResult(intent, 0);
//================== ===============================================
//11.打開Google Market
// 打開Google Market直接進入程式的詳細頁面
Uri uri = Uri.parse("market://details?id=" + "com.demo.app ");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
##//=============== ================================================
##//12.進入手機設定介面:
// 進入無線網路設定介面(其它可舉一反三)
Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); (intent, 0);
//==================================== ===========================
//13.安裝apk:
Uri installUri = Uri.fromParts( "package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
#//================ =================================================
//14.卸載apk:
Uri uri = Uri.fromParts("package", strPackageName, null);
約庫) it);
//========================================= ========================
//15.發送附件:
Intent it = new Intent(Intent.ACTION_SEND) ;
###################################################################1正it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///cardcard/eoe.mp3"); /mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//==================== ===============================================
//16.進入聯絡人頁面:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(People.CONTENT_URI);
intent);
//======================================= ========================
//17.查看指定聯絡人:
Uri personUri = ContentUris. withAppendedId(People.CONTENT_URI, info.id);//info.id聯絡人ID
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(personUri );
startActivity(intent);
//================================== ===============================
//18.呼叫系統編輯新增聯絡人(高版本SDK有效):
Intent it = newIntent(Intent.ACTION_INSERT_OR_EDIT);
it.setType("vnd.android.cursor.item/contact"); ;
it.putExtra("name","myName");
it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY, "organization"); provider.Contacts.Intents.Insert.EMAIL,"email");
it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone"); Contacts.Intents.Insert.SECONDARY_PHONE,"mobilePhone");
it.putExtra( android.provider.Contacts.Intents.Insert.TERTIARY_PHONE,"workPhone"); Intents.Insert.JOB_TITLE,"title");
startActivity(it);
//========================= ========================================
//19.呼叫系統編輯新增聯絡人(全有效):
Intent intent = newIntent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(People.CONTENT_ITEM_TYPE); , "My Name");
#intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");
intent.putExtra(Contacts.Intoness.Inert
Intent.putExtra(Contacts.Intents.Insert.EMAIL,“com@com.com”);
intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, Contacts.ContactMethodsColumns.TYPE_WORK);
startActivity(意圖);
//================================== == =============================
//20.開啟另一個程式
Intent i = new意圖();
ComponentName cn = new ComponentName("com.example.jay.test",
"com.example.jay.test.MainActivity");
i.setComponent(cn);
i.setAction("android.intent.action.MAIN");
startActivityForResult(i, RESULT_OK);
//================================ == ===============================
//21.開啟錄音機
Intent mi = new意圖(Media.RECORD_SOUND_ACTION);
startActivity(mi);
//================================== == =============================
//22.來自google內容搜尋
意圖意圖=新意圖();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);
//===================== == =============================================
#6.Action在哪裡查? 本來想直接貼以前收集到的Intent Action的,後來想想還是算了,授之以魚,還不如授之以漁, 如果你下載了Android的文檔的話,可以在前面路徑:sdk-->docs-->reference-->android--->content--->Intent.html 找到這個遊戲意,然後從這個常數開始就是了:遇到陌生人的自己找查即可~
本節小結:
#好的,關於Intent的基本使用就到這裡,下一節我們會來繼續學習在日常開發中使用Intent可能會遇到 的一些問題或者說需求吧,寶寶期待,謝謝~