现在的位置: 首页 > 综合 > 正文

Android Create Shortcut

2013年09月04日 ⁄ 综合 ⁄ 共 2338字 ⁄ 字号 评论关闭

Add permission:

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

Code:

private void setUpShortCut() {

        Intent intent = new Intent(CREATE_SHORTCUT_ACTION);

        // 设置快捷方式图片
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this, R.drawable.logo));

        // 设置快捷方式名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina");

        // 设置是否允许重复创建快捷方式 false表示不允许
        intent.putExtra("duplicate", false);
        
        // 设置快捷方式要打开的intent
        // 第一种方法创建快捷方式要打开的目标intent
        Intent targetIntent = new Intent();
        // 设置应用程序卸载时同时也删除桌面快捷方式
        targetIntent.setAction(Intent.ACTION_MAIN);
        targetIntent.addCategory("android.intent.category.LAUNCHER");
        
        ComponentName componentName = new ComponentName(getPackageName(), this.getClass().getName());
        targetIntent.setComponent(componentName);
        
        // 第二种方法创建快捷方式要打开的目标intent
        
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);

        // 发送广播
        sendBroadcast(intent);
}

    
    private void tearDownShortCut() {

        Intent intent = new Intent(DROP_SHORTCUT_ACTION);
        // 指定要删除的shortcut名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina");

        String appClass = getPackageName() + "." + this.getLocalClassName();

        ComponentName component = new ComponentName(getPackageName(), appClass);
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent().setAction(Intent.ACTION_MAIN).setComponent(component));
        sendBroadcast(intent);

}

 

Or:

if (Intent.ACTION_CREATE_SHORTCUT.equals(action))
{
 setupShortcut();
 finish();
 return;
}
 
...
private void setupShortcut() {
 // First, set up the shortcut intent.
 //For this example, we simply create an intent that
 // will bring us directly back to this activity.
 //A more typical implementation would use a
 // data Uri in order to display a more specific result,
 //or a custom action in order to
 // launch a specific operation.
 
 Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
 shortcutIntent.setClassName(this, this.getClass().getName());
 shortcutIntent.putExtra(EXTRA_KEY, "ApiDemos Provided This Shortcut");
 
 // Then, set up the container intent (the response to the caller)
 
 Intent intent = new Intent();
 intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_name));
 Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
 this,  R.drawable.app_sample_code);
 intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
 
 // Now, return the result to the launcher
 
 setResult(RESULT_OK, intent);
}

抱歉!评论已关闭.