Android_如何创建桌面快捷方式

在Android官方的room(当然其他room有可能是,有可能不是,如MiUi就不是)程序安装之后,程序的图片是放到主界面抽屉里面的。

用户每次使用的时候都需要先打开抽屉然后选择应用程序,这样相当的不方面,当然用户可以自己将程序图标放到桌面上去,但是如果,

我们想再程序中去实现这个问题,那该如何呢?


  1. public static void createShortCut(Context context) {  
  2.     final Intent addIntent = new Intent(  
  3.             "com.android.launcher.action.INSTALL_SHORTCUT");  
  4.     final Parcelable icon = Intent.ShortcutIconResource.fromContext(  
  5.             context, R.drawable.icon); // 获取快捷键的图标  
  6.     addIntent.putExtra("duplicate"false);   
  7.     final Intent myIntent = new Intent(context,XX.class);  
  8.     addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,  
  9.             context.getString(R.string.mobile_site_shortcut_name));// 快捷方式的标题  
  10.     addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);// 快捷方式的图标  
  11.     addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);// 快捷方式的动作  
  12.     context.sendBroadcast(addIntent);  
  13. }  

代码中如此,然后在AndroidMainifest.xml中添加一个权限:

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

这样即可。

你使用的时候,你可能会发现这样的方式来创建快捷方式,只是对程序的主Activity其作用,也就是含有:

  1. <intent-filter>  
  2.                 <action android:name="android.intent.action.MAIN" />  
  3.                 <category android:name="android.intent.category.LAUNCHER" />  
  4.             </intent-filter>  

这样标签的Activity其作用,那么如何给指定的一个Acitivity创建一个快捷方式呢?

其实也很简单,你只需要给你的Activity种添加:

  1. <intent-filter>    
  2.             <action android:name="android.intent.action.CREATE_SHORTCUT" />    
  3.         </intent-filter>   


该标签即可。

///////////////////////////////////另一种方式///////////////////////////////////

	private void creatdeskicon() {//创建桌面图标
		 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.ic_launcher);  
		    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);  
		          
		    sendBroadcast(shortcut);   

	}
原文地址:https://www.cnblogs.com/clarence/p/3401081.html