给应用创建快捷图标

权限:

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

package com.example.t02;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        Button btnChange;
        
        public static final String ACTION_ADD_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
        
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            
            btnChange = (Button)rootView.findViewById(R.id.btnChange);
            
            btnChange.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View arg0) {
                    addShortcut("tttt");
                }
            });
            
            return rootView;
        }
        
        private void addShortcut(String name) {
            Intent addShortcutIntent = new Intent(ACTION_ADD_SHORTCUT);

            // 不允许重复创建
            addShortcutIntent.putExtra("duplicate", false);//

            // 名字
            addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);

            // 图标
            addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                    Intent.ShortcutIconResource.fromContext(getActivity(),
                            R.drawable.ic_launcher2));

            // 设置关联Activity
            Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
            launcherIntent.setClass(getActivity(), MainActivity.class);
            launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

            addShortcutIntent
                    .putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);

            // 发送广播
            getActivity().sendBroadcast(addShortcutIntent);
        }
    }

}
原文地址:https://www.cnblogs.com/yshyee/p/4782928.html