Android桌面快捷方式图标生成与删除,使用Intent与launcher交互

来源:互联网 发布:国内程序员办公环境 编辑:程序博客网 时间:2024/04/27 20:17
 

通过分析Launcher的生成快捷方式的过程,找出了使用Intent发送请求,Launcher通过自己注册的InstallShortCutReceiver和UnInstallShortCutReceiver实现了快捷方式图标的生成与移除过程。本文主要分析外部apk如何使用Intent请求生成快捷方式和移除快捷方式图标的问题。

 

生成快捷方式代码:

 

Java代码  收藏代码
  1. private static final String ACTION_INSTALL_SHORTCUT =   
  2.     "com.android.launcher.action.INSTALL_SHORTCUT";  
  3.       
  4. /** 
  5.  * 是否可以有多个快捷方式的副本 
  6. */  
  7. static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";  
  8.   
  9. Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);    
  10.         shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,    
  11.                 getString(R.string.app_name));    
  12.        // 是否可以有多个快捷方式的副本,参数如果是true就可以生成多个快捷方式,如果是false就不会重复添加         
  13.          shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);    
  14.         Intent intent2 = new Intent(Intent.ACTION_MAIN);    
  15.         intent2.addCategory(Intent.CATEGORY_LAUNCHER);  
  16.   
  17. // 要删除的应用程序的ComponentName,即应用程序包名+activity的名字  
  18.         intent2.setComponent(new ComponentName(this.getPackageName(),    
  19.                 this.getPackageName()+".Main"));    
  20.             
  21.         shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);    
  22.         shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,    
  23.                 Intent.ShortcutIconResource.fromContext(this,    
  24.                         R.drawable.icon));    
  25.         sendBroadcast(shortcutIntent);  

 注:Intent intent2 = new Intent(Intent.ACTION_MAIN);  这个也可以换成的构造参数也可以是Intent.ACTION_CREATE_SHORTCUT,也可以生成快捷方式图标,但是这样不标准,在删除的时候如果不和这个对于相同则无法删除。所以还是用Intent.ACTION_MAIN。

 

那么删除快捷方式的代码是:

Java代码  收藏代码
  1. private static final String ACTION_UNINSTALL_SHORTCUT =   
  2. "com.android.launcher.action.UNINSTALL_SHORTCUT";  
  3.   
  4.    
  5.   
  6. Intent intent = new Intent(ACTION_UNINSTALL_SHORTCUT );  
  7.   intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);  
  8. // 要删除的应用程序的ComponentName,即应用程序包名+activity的名字  
  9.  ComponentName comp = new ComponentName(info.activityInfo.packageName,  
  10.     info.activityInfo.name);  
  11.   intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent()  
  12.   .setComponent(comp).setAction("android.intent.action.MAIN"));  
  13.   sendBroadcast(intent);  
  14.   
  15.   
  16. 最后要记得加上权限:  
  17. 添加的权限:<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>  
  18. 删除的权限:<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>  
原创粉丝点击