要特别注意以下这句话导致的无法创建快捷方式的问题
intent.putExtra("duplicate", false);很多地方都说这句话的意义是在于防止重复创建快捷方式,但是我今天遇到的问题就是由于这句话导致无法在桌面上创建快捷方式。
最后我的做法是:
1.用SharedPreferences来判断是否是第一次进入应用
2.用isInstallShortcut()来判断是否存有快捷方式
3.创建快捷方式(没有duplicate属性)
1.
private void createShortCut() { SharedPreferences userini = getSharedPreferences( getString(R.string.useriniXML), Activity.MODE_PRIVATE); Log.e("H3c","sh.."+userini.getInt("seflshotcut", 0)); if (userini.getInt("seflshotcut", 0) == 0) { m_tool.createShortCut(Main.this); SharedPreferences.Editor sEdi = userini.edit(); sEdi.putInt("seflshotcut", 1); sEdi.commit(); } }2.
private boolean isInstallShortcut() { boolean isInstallShortcut = false; final ContentResolver cr = MarketApplication .getMarketApplicationContext().getContentResolver(); String AUTHORITY = "com.android.launcher.settings"; Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { "XXXX" }, null); if (c != null && c.getCount() > 0) { isInstallShortcut = true; } if (c != null) { c.close(); } if (isInstallShortcut) { return isInstallShortcut; } AUTHORITY = "com.android.launcher2.settings"; CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { "XXXX" }, null); if (c != null && c.getCount() > 0) { isInstallShortcut = true; } return isInstallShortcut; } /** * 创建快捷方式 * */ public void createShortCut(Context contxt) { if (isInstallShortcut()) {// 如果已经创建了一次就不会再创建了 return; } Intent sIntent = new Intent(Intent.ACTION_MAIN); sIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后,程序卸载的时候才会主动将该快捷方式也卸载 sIntent.setClass(contxt, Login.class); Intent installer = new Intent();// installer.putExtra("duplicate", false); installer.putExtra("android.intent.extra.shortcut.INTENT", sIntent); installer.putExtra("android.intent.extra.shortcut.NAME", "XXXX"); installer.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", Intent.ShortcutIconResource.fromContext(contxt, R.drawable.icon)); installer.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); contxt.sendBroadcast(installer); }测试:点击