先定義兩個函數:
public void addShortCut(){ Intent addIntent=new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); String myTitle=getResources().getString(R.string.app_name); Parcelable icon=Intent.ShortcutIconResource.fromContext(this,R.drawable.app); //設定點擊捷徑操作後的Intent //Intent myIntent=new Intent(this,Start.class); // 是否允許重複建立 addIntent.putExtra("duplicate", false); Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setClass(this,Start.class); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,myTitle); addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon); addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,intent); sendBroadcast(addIntent); } public boolean IfaddShortCut(){ boolean isInstallShortcut = false ; final ContentResolver cr = AppstoreActivity.this.getContentResolver(); final String AUTHORITY = "com.android.launcher2.settings"; final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); Cursor c = cr.query(CONTENT_URI, new String[] {"title","iconResource" }, "title=?", new String[] {getString(R.string.app_name ) }, null); if(c!=null && c.getCount()>0){ isInstallShortcut = true ; } return isInstallShortcut ; }
然後在程式啟動時:
//建立捷徑 boolean flag =IfaddShortCut();//如果已經建立,則不需要在建立 if(flag==false){ addShortCut(); }