編輯:關於 Android 程式設計
Intent 真正的威力在於隱式 Intent,而隱式 Intent 必須搭配 intent-filter 才能發揮作用,關於這部分的基礎概念可參考〈Android 官方文件之 App Components(Intents and Intent Filters)〉。
隱式 Intent 強大到系統乾脆預先準備了一整套現成的 Intent,讓我們直接就能叫起系統應用程式。本文整理常用的隱式 Intent,以及自定義 intent-filter 去匹配它們的方式。原始文件可參考官方章節 Common Intents。
以下依目標元件的類別分類說明。所有範例都遵循同一個安全寫法:先呼叫 resolveActivity() 確認有 App 能處理,再 startActivity(),避免 ActivityNotFoundException。
Action:ACTION_SET_ALARM;Data URI 與 MIME Type 皆為空。
Extras:
EXTRA_HOUR:小時
EXTRA_MINUTES:分鐘
EXTRA_MESSAGE:自訂提示訊息
EXTRA_DAYS:每週重複響鈴的星期,值為 ArrayList,元素取自 Calendar 的靜態常數(如 Calendar.MONDAY);一次性鬧鐘不必設定
EXTRA_RINGTONE:鈴聲,值為 scheme 是 content: 的 URI,指向一個音訊檔;也可設為 VALUE_RINGTONE_SILENT 表示靜音
EXTRA_VIBRATE:是否同時震動,boolean
EXTRA_SKIP_UI:是否跳過設定介面,boolean;為 true 時不顯示 dialog,直接進入鬧鐘設定畫面
public void createAlarm(String message, int hour, int minutes) {
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)
.putExtra(AlarmClock.EXTRA_MESSAGE, message)
.putExtra(AlarmClock.EXTRA_HOUR, hour)
.putExtra(AlarmClock.EXTRA_MINUTES, minutes);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}需要宣告的權限:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />可響應此 Intent 的 intent-filter:
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>注意:此 Intent 僅相容 Android 4.4(API 19)以上版本。
Action:ACTION_SET_TIMER;Data URI 與 MIME Type 皆為空。
Extras:
EXTRA_LENGTH:倒數秒數
EXTRA_MESSAGE:計時結束的提示訊息
EXTRA_SKIP_UI:是否跳過設定介面,boolean
public void startTimer(String message, int seconds) {
Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
.putExtra(AlarmClock.EXTRA_MESSAGE, message)
.putExtra(AlarmClock.EXTRA_LENGTH, seconds)
.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}權限與 intent-filter 同上(com.android.alarm.permission.SET_ALARM 與 DEFAULT category)。
注意:此 Intent 僅相容 Android 4.4(API 19)以上版本。
Action:ACTION_SHOW_ALARMS;Data URI 與 MIME Type 皆為空,intent-filter 只需宣告 DEFAULT category。
Action:ACTION_INSERT
Data URI:Events.CONTENT_URI
MIME Type:vnd.android.cursor.dir/event
Extras:
EXTRA_EVENT_ALL_DAY:是否為全天事件,boolean
EXTRA_EVENT_BEGIN_TIME:事件起始時間,毫秒數
EXTRA_EVENT_END_TIME:事件結束時間,毫秒數
TITLE:事件標題
DESCRIPTION:事件描述
EVENT_LOCATION:地點
EXTRA_EMAIL:以郵件形式邀請參與者,多個信箱以逗號分隔
更多欄位可參考 CalendarContract.EventsColumns。
public void addEvent(String title, String location, Calendar begin, Calendar end) {
Intent intent = new Intent(Intent.ACTION_INSERT)
.setData(Events.CONTENT_URI)
.putExtra(Events.TITLE, title)
.putExtra(Events.EVENT_LOCATION, location)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}對應的 intent-filter:
<intent-filter>
<data android:mimeType="vnd.android.cursor.dir/event" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>Action:ACTION_IMAGE_CAPTURE 或 ACTION_VIDEO_CAPTURE;Data URI 與 MIME Type 皆為空。
Extras:EXTRA_OUTPUT,值是一個 Uri,代表照片或影片的存放位置,稍後可在 onActivityResult() 中透過它讀取檔案。
注意:使用 ACTION_IMAGE_CAPTURE 時,回傳 Intent 中鍵為 "data" 的值只是一張縮圖(thumbnail),並非原始解析度的照片。
static final int REQUEST_IMAGE_CAPTURE = 1;
static final Uri mLocationForPhotos;
public void capturePhoto(String targetFilename) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.withAppendedPath(mLocationForPhotos, targetFilename));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getParcelableExtra("data");
// 原圖已存在 mLocationForPhotos 指定的位置,接著處理它
}
}更完整的做法可參考官方 Training:Taking Photos Simply、Taking Videos Simply。此 Action 的 intent-filter 只需宣告 DEFAULT category。
Action:INTENT_ACTION_STILL_IMAGE_CAMERA;Data URI、MIME Type、Extras 皆為空。
public void capturePhoto() {
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}Action:INTENT_ACTION_VIDEO_CAMERA;其餘欄位皆為空,寫法與上例相同,只需替換 action 常數。
Action:ACTION_PICK
MIME Type:Contacts.CONTENT_TYPE
若只是透過 ACTION_PICK 取得 Uri 再用 Contacts Provider 讀取資料,不需要申請 READ_CONTACTS 權限。
static final int REQUEST_SELECT_CONTACT = 1;
public void selectContact() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_CONTACT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_CONTACT && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
// 接著處理 contactUri
}
}Action:ACTION_PICK,透過 MIME Type 指定想要的資料種類:
CommonDataKinds.Phone.CONTENT_TYPE:號碼
CommonDataKinds.Email.CONTENT_TYPE:電子郵件
CommonDataKinds.StructuredPostal.CONTENT_TYPE:郵寄地址
CommonDataKinds 底下還有許多其他欄位可取。
static final int REQUEST_SELECT_PHONE_NUMBER = 1;
public void selectPhoneNumber() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberIndex);
// 接著處理號碼
}
}
}Action:ACTION_VIEW
Data URI:content:<URI>,指向要檢視的聯絡人。
取得這個 Uri 有兩條路:一是沿用上一小節 ACTION_PICK 的回傳值,不需任何權限;二是自行查詢通訊錄清單,這就需要 READ_CONTACTS 權限。
public void viewContact(Uri contactUri) {
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}Action:ACTION_EDIT
Data URI:content:<URI>(取得方式與權限同上)
MIME Type:由 Uri 決定
Extras:ContactsContract.Intents.Insert
public void editContact(Uri contactUri, String email) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(contactUri);
intent.putExtra(Intents.Insert.EMAIL, email);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}更多做法可參考 Training:Modifying Contacts Using Intents。
Action:ACTION_INSERT
MIME Type:Contacts.CONTENT_TYPE
Extras:ContactsContract.Intents.Insert
public void insertContact(String name, String email) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType(Contacts.CONTENT_TYPE);
intent.putExtra(Intents.Insert.NAME, name);
intent.putExtra(Intents.Insert.EMAIL, email);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}Action 依附件數量選擇:ACTION_SENDTO(無附件)、ACTION_SEND(單一附件)、ACTION_SEND_MULTIPLE(多個附件)。
MIME Type:text/plain 或 */*
Extras:
Intent.EXTRA_EMAIL:收件人,字串陣列
Intent.EXTRA_CC:副本收件人,字串陣列
Intent.EXTRA_BCC:密件副本收件人,字串陣列
Intent.EXTRA_SUBJECT:主旨
Intent.EXTRA_TEXT:內文
Intent.EXTRA_STREAM:附件的 Uri;若為 ACTION_SEND_MULTIPLE,值應為 ArrayList<Uri>
public void composeEmail(String[] addresses, String subject, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}如果你希望只讓郵件 App 出現在選單裡(而不是社交或簡訊 App),改用 ACTION_SENDTO 並把 Uri 設為 mailto::
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // 只有郵件 App 會處理
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}對應的 intent-filter 需同時宣告 */* 與 mailto scheme 兩組。
Action:ACTION_GET_CONTENT,並指定想要的 MIME 類型。回傳的檔案參照只在該 Activity 生命週期內短暫有效,若要長期保留,App 必須自行複製一份留下來。此 Intent 也允許在當前進程中建立新檔案。
在 onActivityResult() 中可取回包含 Uri 的 Intent,其 scheme 可能是 http:、content: 或 file: 等任意型別。若你只希望結果來自 ContentProvider(也就是 content: 這類可透過 openFileDescriptor() 開啟串流的來源),請加上 CATEGORY_OPENABLE 類別。
Android 4.3(API 18)以上還可以加入 EXTRA_ALLOW_MULTIPLE 並設為 true 以支援多選,結果會透過 Intent.getClipData() 回傳。
Extras:
EXTRA_ALLOW_MULTIPLE:是否可一次選擇多個檔案,boolean
EXTRA_LOCAL_ONLY:是否只允許本地檔案(選完立刻可用,不需等待下載),boolean
Category(選填):CATEGORY_OPENABLE
static final int REQUEST_IMAGE_GET = 1;
public void selectImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_GET);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getParcelableExtra("data");
Uri fullPhotoUri = data.getData();
// 接著處理 fullPhotoUri 指向的圖片
}
}intent-filter 需宣告 image/* 與 CATEGORY_OPENABLE。
Android 4.4 以上提供 ACTION_OPEN_DOCUMENT 與 ACTION_CREATE_DOCUMENT,能開啟其他 App 的文件並長期持有存取權。
Extras:
EXTRA_MIME_TYPES:想要類型的 MIME 陣列,至少要包含 */*
EXTRA_ALLOW_MULTIPLE:是否可多選
EXTRA_TITLE:對應 ACTION_CREATE_DOCUMENT,新檔案的標題
EXTRA_LOCAL_ONLY:是否限定本地檔案
static final int REQUEST_IMAGE_OPEN = 1;
public void openImage() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// ACTION_OPEN_DOCUMENT 只有系統會接收,不需做 resolveActivity 檢查
startActivityForResult(intent, REQUEST_IMAGE_OPEN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_OPEN && resultCode == RESULT_OK) {
Uri fullPhotoUri = data.getData();
// 接著處理 fullPhotoUri 指向的圖片
}
}若自己的 App 要提供檔案給 ACTION_OPEN_DOCUMENT 使用,ContentProvider 需這樣宣告:
<provider ...
android:grantUriPermissions="true"
android:exported="true"
android:permission="android.permission.MANAGE_DOCUMENTS">
<intent-filter>
<!-- 宣告支援 ACTION_OPEN_DOCUMENT -->
</intent-filter>
</provider>Action:ACTION_VIEW;MIME Type 為空。Data URI 支援以下 geo: 格式:
geo:<latitude>,<longitude>:顯示指定座標,例如 geo:47.6,-122.3geo:<latitude>,<longitude>?z=<zoom>:指定縮放層級,1 最遠(全球視野,中心為該座標),23 最接近地面,例如 geo:47.6,-122.3?z=11geo:0,0?q=lat,lng(label):顯示座標並附上標籤,例如 geo:0,0?q=34.99,-106.61(Treasure)geo:0,0?q=<street+address>:以地址搜尋,例如 geo:0,0?q=1600+Amphitheatre+Parkway%2C+CA
重要:geo: URI 中的字串參數必須先做 URL 編碼。例如 1st & Pike, Seattle 應編碼為 1st%20%26%20Pike%2C%20Seattle,空格需換成 %20 或加號,才能傳給 Uri.parse()。
public void showMap(Uri geoLocation) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}intent-filter 需宣告 geo scheme 與 DEFAULT category。
Action:ACTION_VIEW
Data URI:file:<URI>、content:<URI>、http:<URL>
MIME Type:audio/*、application/ogg、application/itunes
public void playMedia(Uri file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(file);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}intent-filter 需宣告對應的 MIME 類型與 DEFAULT category。
Action:ACTION_CREATE_NOTE
MIME Type:PLAIN_TEXT_TYPE 或 */*
Extras:EXTRA_NAME(標題)、EXTRA_TEXT(內容)
public void createNote(String subject, String text) {
Intent intent = new Intent(NoteIntents.ACTION_CREATE_NOTE)
.putExtra(NoteIntents.EXTRA_NAME, subject)
.putExtra(NoteIntents.EXTRA_TEXT, text);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}ACTION_DIAL 只會開啟撥號介面並帶入號碼,由使用者自行按下撥號鍵,不需要任何權限。ACTION_CALL 則會直接撥出,需要下列權限:
<uses-permission android:name="android.permission.CALL_PHONE" />Data URI:tel:<phone-number> 或 voicemail:<phone-number>;MIME Type 為空。號碼格式規範參閱 IETF RFC 3966,合法範例如下:
tel:2125551212
tel:(212) 555 1212
public void dialPhoneNumber(String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}Action:com.google.android.gms.actions.SEARCH_ACTION,支援 Google Now 語音搜尋。Extras 中的 QUERY 為使用者輸入的關鍵字。若希望自己的 App 能被搜尋到,intent-filter 需宣告 DEFAULT category。
Action:ACTION_SEARCH;Extras:SearchManager.QUERY,字串型別。
public void searchWeb(String query) {
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, query);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}當 App 需要使用者先開啟某項系統功能(例如傳檔前得先開藍牙),可以直接把使用者導引到對應的設定頁。可用的 action 包括:
ACTION_SETTINGS、ACTION_WIRELESS_SETTINGS、ACTION_AIRPLANE_MODE_SETTINGS、ACTION_WIFI_SETTINGS、ACTION_APN_SETTINGS、ACTION_BLUETOOTH_SETTINGS、ACTION_DATE_SETTINGS、ACTION_LOCALE_SETTINGS、ACTION_INPUT_METHOD_SETTINGS、ACTION_DISPLAY_SETTINGS、ACTION_SECURITY_SETTINGS、ACTION_LOCATION_SOURCE_SETTINGS、ACTION_INTERNAL_STORAGE_SETTINGS、ACTION_MEMORY_CARD_SETTINGS
Data URI 與 MIME Type 皆為空。
public void openWifiSettings() {
Intent intent = new Intent(Intent.ACTION_WIFI_SETTINGS);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}Action:ACTION_SENDTO、ACTION_SEND、ACTION_SEND_MULTIPLE
Data URI:sms:<phone_number>、smsto:<phone_number>、mms:<phone_number>、mmsto:<phone_number>(四者效果相同)
MIME Type:text/plain、image/*、video/*
Extras:
"subject":訊息標題,字串,通常僅適用彩信
"sms_body":訊息內容,字串
Intent.EXTRA_STREAM:附件 Uri;若為 ACTION_SEND_MULTIPLE,值應為 ArrayList<Uri>
public void composeMmsMessage(String message, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType(HTTP.PLAIN_TEXT_TYPE);
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}若想確保只有簡訊 App 回應,可改用 ACTION_SEND 搭配 smsto: scheme:
public void composeMmsMessage(String message, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("smsto:")); // 確保只有簡訊 App 會回應
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}intent-filter 需宣告 text/plain、image/* 與 DEFAULT category。
Action:ACTION_VIEW
Data URI:http:<URL>、https:<URL>
MIME Type:text/plain、text/html、application/xhtml+xml、application/vnd.wap.xhtml+xml
public void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}若希望自己的 App 攔截網頁中的連結,intent-filter 需要這樣寫:
<intent-filter>
<!-- 加上 host 屬性可讓 App 只回應自家網域的網址 -->
<data android:scheme="http" android:host="www.example.com" />
<category android:name="android.intent.category.DEFAULT" />
<!-- 想接收網頁中的連結,BROWSABLE 是必需的 -->
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>小結:隱式 Intent 的核心思維是「描述我想要做什麼」,把「怎麼做」交給系統去匹配。實作時務必搭配 resolveActivity() 做防禦,並記得依 Action 的性質補上必要權限。
Android 基於 IIS 的 APK 下載(四):數據下載與安裝
在〈Android 基於 IIS 的 APK 下載(三)用 JSON 傳輸更新數據〉中,我們已從伺服器取得更新資料並呈現到 UI。更新列表每一行末尾都有一個「行為」按鈕,
Android ViewPager 的 PagerTabStrip 與 PagerTitleStrip 用法詳解
零、概覽 1. ViewPager 說白了就是一個控制項,使用時套件名稱要寫全為 Android.support.v4.view.ViewPager。由於我的 ADT-B
無需root,智能電視和機頂盒系統大瘦身清緩存方法
無需Root清理智能電視與機頂盒緩存 智能電視與機頂盒長時間使用後會產生大量緩存,佔用系統空間。相比Root,使用清理工具更安全。 使用當貝助手深度清理 當貝助手可清理
Android 多行文字排版:左右對齊與自動換行的六種做法
需求說明 這個功能要讓多行文字分成左右兩部分:左側是長度不一的標題,右側是描述內容。右側描述必須統一對齊,若內容換行,也要從相同起始位置繼續排。 常見解法 一種方式是自