Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 桌面捷徑的建立與刪除(Create Shortcut)

編輯:關於 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);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved