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

Android 添加桌面图标及卸载后自动删除图标的方法

編輯:關於 Android 程式設計

在某些应用场景下,我们需要在桌面创建一个自定义的快捷方式图标。同时,为了保证在应用卸载后桌面图标也能被自动清除,还需要做一些额外处理。本文将介绍添加和删除桌面图标的实现代码。

1. 创建图标

Intent intent = new Intent();
intent.setClass(this, SplashActivity.class);
Intent addShortcut = new Intent(ACTION_ADD_SHORTCUT);
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
addShortcut.putExtra("duplicate", 0);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
sendBroadcast(addShortcut);

2. 删除图标

Intent intent = new Intent();
intent.setClass(this, SplashActivity.class);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
Intent addShortcut = new Intent(ACTION_ADD_SHORTCUT);
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
addShortcut.putExtra("duplicate", 0);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
sendBroadcast(addShortcut);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");

需要注意的是,为了正确匹配和删除图标,intent 需要带上 android.intent.action.MAIN 的 action 和 android.intent.category.LAUNCHER 的 category 这两个过滤属性。这样桌面系统才能准确定位到对应的快捷方式并进行删除操作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved