閱讀826 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android創建和刪除桌麵快捷方式

原文:https://www.cnblogs.com/-OYK/archive/2011/05/31/2064797.html

注:mapViewActivity為某個Activity


1,判斷是否已經創建了快捷方式(在某些moto的機型中需要判斷)

private boolean hasShortcut()
{
        boolean isInstallShortcut = false;
        final ContentResolver cr = mapViewActivity.getContentResolver();
        final String AUTHORITY ="com.android.launcher.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[] {mapViewActivity.getString(R.string.app_name).trim()}, null);
        if(c!=null && c.getCount()>0){
            isInstallShortcut = true ;
        }
        return isInstallShortcut ;
    }

2, 創建

/** 
 * 為程序創建桌麵快捷方式 
 */ 
private void addShortcut(){  
    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");  
           
    //快捷方式的名稱  
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));  
    shortcut.putExtra("duplicate", false); //不允許重複創建  
           
    //指定當前的Activity為快捷方式啟動的對象: 如 com.everest.video.VideoPlayer  
    //注意: ComponentName的第二個參數必須加上點號(.),否則快捷方式無法啟動相應程序  
    ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName());  
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));  
   
    //快捷方式的圖標  
    ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);  
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);  
           
    sendBroadcast(shortcut);  
}  

3, 刪除

/** 
     * 刪除程序的快捷方式 
     */ 
    private void delShortcut(){  
        Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");  
               
        //快捷方式的名稱  
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));  
               
        //指定當前的Activity為快捷方式啟動的對象: 如 com.everest.video.VideoPlayer  
        //注意: ComponentName的第二個參數必須是完整的類名(包名+類名),否則無法刪除快捷方式  
        String appClass = this.getPackageName() + "." +this.getLocalClassName();  
        ComponentName comp = new ComponentName(this.getPackageName(), appClass);  
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));  
               
        sendBroadcast(shortcut);  
               
    }  

4、 聲明權限

在AndroidManifest.xml 文件中聲明 創建和刪除快捷方式時聲明權限

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />  
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />  




最後更新:2017-04-02 16:47:37

  上一篇:go kindle dxg 作為電腦擴展顯示器
  下一篇:go OpenMP並行計算PI的值