android 快捷方式代码片段随记

    /**
     * 创建桌面快捷方式 一
     */
    private void addShortcutToDesktop(){
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
         // 不允许重建
         shortcut.putExtra("duplicate", false);
         // 设置名字
         shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,this.getString(R.string.app_name));
         // 设置图标
         shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this,
                         R.drawable.ic_launcher));

         // 设置意图和快捷方式关联程序
         shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent(this, this.getClass()).setAction(Intent.ACTION_MAIN));
         // 发送广播
         sendBroadcast(shortcut);
    }
    

/**

*方式二

*/

if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {       

  Intent shortcut = new Intent(Intent.ACTION_CREATE_SHORTCUT);

     // 不允许重建

     shortcut.putExtra("duplicate", false);

     // 设置名字

     shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,

             this.getString(R.string.app_name));

     // 设置图标

     shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,

             Intent.ShortcutIconResource.fromContext(this,

                     R.drawable.ic_launcher));

     // 设置意图和快捷方式关联的程序

     shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,

             new Intent(this, this.getClass()));     

        //将结果返回到launcher

        setResult(RESULT_OK, intent);       

    }

需在xml中设置IntentFilter

<intent-filter>

  <action android:name="android.intent.action.CREATE_SHORTCUT" />

</intent-filter>

 


    /**
     * 判断是否已创建快捷方式
     * @return
     */
    private boolean hasInstallShortcut() {

         boolean hasInstall = false;
         final String AUTHORITY = "com.android.launcher.settings";
         Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");
         Cursor cursor = this.getContentResolver().query(CONTENT_URI,     new String[] { "title", "iconResource" }, "title=?",
               new String[] { this.getString(R.string.app_name) }, null);
         if (cursor != null && cursor.getCount() > 0) {
             hasInstall = true;
         }
         return hasInstall;
     }

 

所需权限:

<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/><!-- 判断所需权限 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/><!-- 创建快捷方式权限 -->

posted @ 2014-02-07 20:51  迷途的天空  阅读(210)  评论(0编辑  收藏  举报