Android自动创建shortcut

为当前Activity创建快捷方式


private void addShortCut(){
    //添加action
    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    //shortcut的名字
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
    //不允许重复添加
    shortcut.putExtra("duplicate", false);
    //设置shortcut的图标
    Parcelable icon = Intent.ShortcutIconResource.fromContext(this,R.drawable.icon);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
    //设置用来启动的intent
    //如果用以下Intent会造成从快捷方式进入和从应用集合进入 会开启两遍SplashActivity的问题
    //解决的关键在于添加Action_Main
    //Intent intent = new Intent(this, SplashActivity.class);
    ComponentName comp = new ComponentName(this.getPackageName(), this.getPackageName() + "." +this.getLocalClassName());
    Intent intent = new Intent(Intent.ACTION_MAIN).setComponent(comp);
    intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
    //发送广播让Launcher接收来创建shortcut
    sendBroadcast(shortcut);
 
}
    
}

判断是否已创建快捷方式

首先需要获取Launcher的授权(此处理解为系统的Launcher.settings的包名),由于安卓的碎片化,每种机型的Laucher包名可能不与官方的相同,因此用以下方法来获取

private String getAuthorityFromPermission(Context context, String permission){
        if (permission == null) return null;
        List packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs != null) {
            for (PackageInfo pack : packs) { 
                ProviderInfo[] providers = pack.providers; 
                if (providers != null) { 
                    for (ProviderInfo provider : providers) { 
                        if (permission.equals(provider.readPermission)) return provider.authority;
                        if (permission.equals(provider.writePermission)) return provider.authority;
                    } 
                }
            }
        }
        return null;
    }
    ```

####然后判断是否已安装快捷方式

```java
private boolean isAddedShortCut(){
        boolean isAdded = false;
        //调用Activity的getContentResolver();
        final ContentResolver cr = getContentResolver();
        String authority = getAuthorityFromPermission(this.getApplicationContext(), "com.android.launcher.permission.READ_SETTINGS");
        //默认"com.android.launcher2.settings";
        final Uri contentUri = Uri.parse("content://"+authority+"/favorites?notify=true");
        Cursor c = cr.query(contentUri, new String[] { "title", "iconResource" }, "title=?"
                , new String[] { getString(R.string.app_name) }, null);
        if(c!=null && c.getCount()>0){
            isAdded = true;
        }
        return isAdded;
    }

注意:在Manifest文件中加入权限 com.android.launcher.action.INSTALL_SHORTCUT

你可能感兴趣的:(Android自动创建shortcut)