編輯:關於 Android 程式設計
想讓使用者一鍵直達某個頁面(例如某家店鋪的詳情頁),可以在執行期動態建立桌面捷徑。整個流程分兩半:先檢查是否已存在,再送出建立廣播。
Android 的桌面(Launcher)會把捷徑存在自己的 favorites 資料表中,因此可以透過 ContentResolver 直接查詢,用標題當作判斷依據:
/**
* 是否已建立捷徑
*/
private boolean hasShortcut() {
boolean isInstallShortcut = false;
final String AUTHORITY = "com.android.launcher.settings";
final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
Cursor c = getContentResolver().query(CONTENT_URI,
new String[] { "title", "iconResource" },
"title=?", new String[] { shopDetail.getTitle() }, null);
if (null != c && c.getCount() > 0) {
isInstallShortcut = true;
}
return isInstallShortcut;
}
/**
* 建立捷徑
*/
private void addShortcut() {
if (hasShortcut()) {
return; // 已存在就不重複建立
}
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
// 捷徑名稱
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
shopDetail.getTitle() + "的店鋪");
// 不允許重複建立
shortcut.putExtra("duplicate", false);
// 指定點擊捷徑時要啟動的目標元件
ComponentName comp = new ComponentName("com.itel.platform",
"com.itel.platform" + "." + "ui.shop.ShopIndexActivity");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
new Intent(Intent.ACTION_MAIN)
.putExtra("shopId", uShopId)
.putExtra("openType", 1)
.setComponent(comp));
// 捷徑圖示:有圖就用圖,沒圖就退回 App 圖示
if (bitmap != null) {
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
} else {
Parcelable icon = Intent.ShortcutIconResource.fromContext(
this, R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
}
// 部分 Android 版本不會顯示提示,這裡手動補一個
if (Build.VERSION.SDK_INT == 10 || Build.VERSION.SDK_INT >= 19) {
Toast.makeText(context,
"快捷鍵 " + shopDetail.getTitle() + "的店鋪 已添加",
Toast.LENGTH_SHORT).show();
}
sendBroadcast(shortcut);
}
權限。送出建立捷徑的廣播需要 com.android.permission.INSTALL_SHORTCUT,缺少它會靜默失敗,不會拋出例外,因此相當難查。
查詢 URI 並非標準。com.android.launcher.settings 這個 authority 是原生 Launcher 的私有實作,各家客製桌面(包括多數大陸廠商 ROM)未必相同,直接查詢可能拿到空結果或拋出例外。實務上較穩妥的做法是把查詢包在 try-catch 裡,並額外維護一份本地已建立的紀錄(例如存進 SharedPreferences)作為主要判斷依據,把系統查詢當成輔助。
Cursor 別忘了關閉。範例中為了精簡省略了 c.close(),實際撰寫時應在 finally 中確保釋放,或改用 try-with-resources。
新版系統的限制。Android 8.0 之後,這個 INSTALL_SHORTCUT 廣播在部分 Launcher 上已不再受支援,改以 ShortcutManager 的 requestPinShortcut() API 為官方途徑,且需要使用者互動確認。若要支援新版本,兩套做法都得實作。
Android 自學筆記(二):我的第一個 HelloWorld
環境裝好了,廢話不多說,直接開工。 建立專案 打開 Eclipse,依序點選 File → New → Android Application Project: 接著就
Android 拍照、選圖與裁剪:告別系統裁剪的兼容性坑
前言:前段時間做項目要用到圖片裁剪,本來調用系統的裁剪功能,結果在我的小米 3 上一直打不開裁剪界面,換一台設備卻又正常。研究了幾款主流 App 的做法發現,淘寶是自己
Android Service 教學:生命週期、startService 與 bindService
Service 是 Android 四大元件之一,適合執行不需要使用者介面的背景工作,例如音樂播放、檔案下載或長時間運算。 兩種啟動方式 startService:呼
Android 基礎:用 CountDownTimer 輕鬆實作倒數計時
在發現這個類別之前,我都是靠 Handler 加子執行緒發消息、再由 UI 執行緒更新顯示的方式來做倒數。前幾天處理一個倒數顯示的需求時無意間找到 CountDownTi