天天看點

Android桌面快捷方式的實作

1)建立 

Android桌面快捷方式的實作
/** 
 * 為程式建立桌面快捷方式 
 */  
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);  
}        
Android桌面快捷方式的實作

2)删除

Android桌面快捷方式的實作
/** 
 * 删除程式的快捷方式 
 */  
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);  
          
}       
Android桌面快捷方式的實作

3) 聲明權限

在AndroidManifest.xml 檔案中聲明 建立和删除快捷方式時聲明權限。

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