標籤:
實現原理:intent的使用,代碼如下:
1 //建立捷徑 2 private void createShortcut() { 3 Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); 4 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); 5 Intent intent = new Intent(Intent.ACTION_MAIN); 6 intent.addCategory(Intent.CATEGORY_LAUNCHER); 7 intent.setClass(this, MainActivity.class);//設定第一個頁面 8 shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent); 9 ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); 10 shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); 11 sendBroadcast(shortcut); 12 Toast.makeText(getApplicationContext(), "建立成功", Toast.LENGTH_SHORT).show();13 } 14 // 判讀是否已經存在捷徑 15 public boolean isExistShortCut() { 16 boolean isInstallShortcut = false; 17 final ContentResolver cr = MainActivity.this.getContentResolver(); 18 final String AUTHORITY = "com.android.launcher2.settings"; 19 final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); 20 Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { getString(R.string.app_name) }, null); 21 if (c != null && c.getCount() > 0) { 22 isInstallShortcut = true; 23 } 24 return isInstallShortcut; 25 }
然後再使用的時候:
1 if(isExistShortCut()){2 Toast.makeText(getApplicationContext(), "捷徑已存在", Toast.LENGTH_SHORT).show();3 }else{4 createShortcut();5 }
記得在資訊清單檔中添加許可權:
1 <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>2 <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>3 <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS"/>
Android 應用添加捷徑