編輯:關於 Android 程式設計
為應用程式在桌面建立捷徑,能讓使用者更快速地進入指定功能。Android 提供了對應的權限與廣播機制來完成這件事,以下說明完整流程。
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/> <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
透過發送 CREATE_SHORTCUT_ACTION 廣播,並設定圖示、名稱與目標 Intent,即可完成捷徑建立:
private void setUpShortCut() {
Intent intent = new Intent(CREATE_SHORTCUT_ACTION);
// 設置快捷方式圖片
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, R.drawable.logo));
// 設置快捷方式名稱
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina");
// 設置是否允許重複創建快捷方式,false 表示不允許
intent.putExtra("duplicate", false);
// 設置快捷方式要打開的目標 intent
Intent targetIntent = new Intent();
targetIntent.setAction(Intent.ACTION_MAIN);
targetIntent.addCategory("android.intent.category.LAUNCHER");
ComponentName componentName = new ComponentName(getPackageName(), this.getClass().getName());
targetIntent.setComponent(componentName);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);
// 發送廣播
sendBroadcast(intent);
}
發送 DROP_SHORTCUT_ACTION 廣播並指定捷徑名稱,即可移除對應捷徑:
private void tearDownShortCut() {
Intent intent = new Intent(DROP_SHORTCUT_ACTION);
// 指定要刪除的 shortcut 名稱
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina");
String appClass = getPackageName() + "." + this.getLocalClassName();
ComponentName component = new ComponentName(getPackageName(), appClass);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
new Intent().setAction(Intent.ACTION_MAIN).setComponent(component));
sendBroadcast(intent);
}
若希望由啟動器發起建立捷徑的請求,可在 Activity 中攔截 ACTION_CREATE_SHORTCUT,再透過 setResult 回傳結果:
if (Intent.ACTION_CREATE_SHORTCUT.equals(action))
{
setupShortcut();
finish();
return;
}
...
private void setupShortcut() {
// First, set up the shortcut intent.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, this.getClass().getName());
shortcutIntent.putExtra(EXTRA_KEY, "ApiDemos Provided This Shortcut");
// Then, set up the container intent (the response to the caller)
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_name));
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
this, R.drawable.app_sample_code);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
}
Android 自定義控制項入門:Canvas 與 Paint 繪製基礎圖形詳解
前言 上一篇寫自定義 View 已經是大半年前的事了,其間一直想接著寫,但總覺得自己火候不夠,怕誤人子弟。這段時間專案剛收尾,終於有點空檔,於是跟著前輩們的思路,把自定義
Service 入門:生命週期、呼叫順序與背景服務模擬
Service 是 Android 中常用於背景任務的元件。它可以透過 startService 啟動,也可以透過 bindService 與其他元件建立綁定。本文以簡單
ListView 固定頭標的實作分享
ListView 固定頭標 近期剛好有固定 ListView 頭部的需求,做法其實很簡單:為 ListView 增加一個 headView,再依滑動距離來判斷是否顯示或隱
Android 高級控件實戰:ViewPager、GridView、PopupWindow 與 SlidingMenu(下)
本文承接上篇,繼續動手實作幾個常見的高級控件,並附上一些實用的小技巧。 常用屏幕與隱藏操作 鎖定屏幕方向:android:screenOrientation=locked