Android 应用添加快捷方式

实现原理:intent的使用,代码如下:
 1 //创建快捷方式
 2     private void createShortcut() {  
 3         Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");  
 4         shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));  
 5         Intent intent = new Intent(Intent.ACTION_MAIN);  
 6         intent.addCategory(Intent.CATEGORY_LAUNCHER);  
 7         intent.setClass(this, MainActivity.class);//设置第一个页面  
 8         shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);  
 9         ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);  
10         shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);  
11         sendBroadcast(shortcut);  
12         Toast.makeText(getApplicationContext(), "创建成功", Toast.LENGTH_SHORT).show();
13     }  
14     // 判读是否已经存在快捷方式  
15     public boolean isExistShortCut() {  
16         boolean isInstallShortcut = false;  
17         final ContentResolver cr = MainActivity.this.getContentResolver();  
18         final String AUTHORITY = "com.android.launcher2.settings";  
19         final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");  
20         Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { getString(R.string.app_name) }, null);  
21         if (c != null && c.getCount() > 0) {  
22             isInstallShortcut = true;  
23         }  
24         return isInstallShortcut;  
25     } 
然后再使用的时候:
1 if(isExistShortCut()){
2     Toast.makeText(getApplicationContext(), "快捷方式已存在", Toast.LENGTH_SHORT).show();
3 }else{
4     createShortcut();
5 }

 记得在清单文件中添加权限:

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

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。