andorid添加桌面快捷方式

布局文件中就一个Button,设置一个点击事件,点击该Button就在桌面添加快捷方式,布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.add_shortcut.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="add shortcut"
        android:id="@+id/btn_add_shortcut"/>
</RelativeLayout>
编写MainActivity代码如下:

<span style="font-size:14px;">public class MainActivity extends AppCompatActivity {
    private Button addShortcutBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addShortcutBtn = (Button) findViewById(R.id.btn_add_shortcut);
        addShortcutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  创建添加快捷方式的intent
                Intent addIntent = new Intent("com.android.launcher." +
                        "action.INSTALL_SHORTCUT");
                //  获取快捷方式的名称
                String title = getResources().getString(R.string.title);
                //  获取快捷方式的图标
                Parcelable icon = Intent.ShortcutIconResource.fromContext(MainActivity.this,
                        R.mipmap.ic_launcher);
                Intent shortcutIntent = new Intent(MainActivity.this,MainActivity.class);
                //  设置快捷方式的标题
                addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,title);
                //  设置快捷方式的图像
                addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,icon);
                //  设置快捷方式的intent
                addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,shortcutIntent);
                //  以广播的方式添加快捷方式
                sendBroadcast(addIntent);
            }
        });
    }
}</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值