andorid添加桌面快捷方式

来源:互联网 发布:松下fp xh编程手册 编辑:程序博客网 时间:2024/04/29 14:43

布局文件中就一个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>



0 0
原创粉丝点击