大家都知道在Android系统中,可以通过拖动图标到桌面来创建快捷方式,今天我们来看一下如何在程序中直接创建程序的快捷图标。
新建一个工程,在布局文件中放入两个按钮,如图:
布局文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
android:orientation
=
"vertical"
>
<
Button
android:id
=
"@+id/create"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"创建快捷方式"
/>
<
Button
android:id
=
"@+id/exit"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"退出"
/>
</
LinearLayout
>
|
布局很简单,我们点一下创建快捷方式按钮,就会在桌面生成我们要的图标了。
下面一起看看实现代码:
1
2
3
4
5
6
7
|
Intent addIntent =
new
Intent(
"com.android.launcher.action.INSTALL_SHORTCUT"
);
Parcelable icon = Intent.ShortcutIconResource.fromContext(MainActivity.
this
, R.drawable.androidchina);
Intent myIntent =
new
Intent(MainActivity.
this
, MainActivity.
class
);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
"快捷方式"
);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);
sendBroadcast(addIntent);
|
需要定义一个快捷图标,以及一个Intent,由Intent告诉系统你是要创建一个快捷方式以及快捷方式的名称等信息。
点一下按钮,就会发现在桌面上已经生成了需要的快捷方式了。
源码下载:点击下载
转载请注明:Android开发中文站 » 创建快捷图标