【Android开发总结(1)】桌面快捷方式创建、删除、查询等方式

来源:互联网 发布:php宠物商城源代码 编辑:程序博客网 时间:2024/06/03 21:53

      最近在对项目进行开发的过程中,增加了一个新功能,就是在应用退出的时候,增加了一个默认勾选创建快捷方式的功能,以便能够把应用添加到桌面快捷方式,以方便用户的使用。接下来就对快捷方式的创建、删除、查询等进行详细讲解。

 

    1、创建快捷方式:

    

Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");// 快捷方式的名称shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,act.getString(R.string.app_name));shortcut.putExtra("duplicate", false); // 不允许重复创建// 指定当前的Activity为快捷方式启动的对象: 如 com.eric.demo.SplashActivity// 注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序ComponentName comp = new ComponentName(act.getPackageName(), ".xxxx启动应用的类名");shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));// 快捷方式的图标ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(act, R.drawable.icon);shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);act.sendBroadcast(shortcut);


除此之外,还有必须要做的就是给应用授权:

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

    2. 删除快捷方式

     Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");// 快捷方式的名称shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,act.getString(R.string.app_name));// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer// 注意: ComponentName的第二个参数必须是完整的类名(包名+类名),类名为在AndroidManifest.xml中定义Action为Main的Activity类,否则无法删除快捷方式String appClass = act.getPackageName() + ".类名";ComponentName comp = new ComponentName(act.getPackageName(), appClass);shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));act.sendBroadcast(shortcut);

同样,我们也要为此方法授权:

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


    3. 查询创建快捷方式是否已经被创建。

boolean isInstallShortcut = false;final ContentResolver cr = ctx.getContentResolver();final String AUTHORITY ;//在andriod 2.1即SDK7以上,是读取launcher.settings中的favorites表的数据;//在andriod 2.2即SDK8以上,是读取launcher2.settings中的favorites表的数据。if(getSystemVersion() < 8){ AUTHORITY = "com.android.launcher.settings";         }else{         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[] { ctx.getString(R.string.app_name).trim() }, null);if (c != null && c.getCount() > 0) {isInstallShortcut = true;}return isInstallShortcut;
 

       /** * 返回系统SDK版本号 * @return */public static int getSystemVersion() {return android.os.Build.VERSION.SDK_INT;}


 

老样子,我们还是要为此授权:

<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" /><uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />

 

OK了,以上就是创建、删除、查询快捷方式的是那种方式。

第一次写技术文章,如果出入,望指正。