创建桌面快捷方式 | 您所在的位置:网站首页 › 如何创建桌面快捷 › 创建桌面快捷方式 |
添加桌面快捷方式,非常简单,只需三步: 1、创建一个添加快捷方式的Intent,该Intent的Action为com.android.launcher.action.INSTALL_SHORTCUT。 2、通过为该Intent添加Extra属性来设置快捷方式的标题、图标及快捷方式对应启动的程序。 3、调用sendBroadcast()方法发送广播即可添加快捷方式。 下面用一个简单示例来演示,在该应用程序中,只给出了添加桌面快捷方式的内容,程序的具体应用无须给出,第一次安装该程序后,会在桌面创建快捷方式,以后不会再创建快捷方式。代码如下: Activity: package com.home.activity; import com.example.testshortcut.R; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Parcelable; import android.widget.Toast; public class TestShortcutActivity extends Activity { private SharedPreferences sp; private Editor editor; private int count = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 获取SharedPreferences对象 sp = this.getSharedPreferences("testshortcut", MODE_PRIVATE); // 得到Editor对象 editor = sp.edit(); // 读取SharedPreferences对象中键为count的值 int readCount = sp.getInt("count", 0); if (readCount > 0) { Toast.makeText(this, "快捷方式已存在,不必再创建", Toast.LENGTH_LONG).show(); return; } // 创建添加快捷方式的Intent Intent addIntent = new Intent( "com.android.launcher.action.INSTALL_SHORTCUT"); // 快捷方式的标题 String title = "我的应用"; // 加载快捷方式图标 Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); // 创建点击快捷方式后再次启动的程序,这里启动自己 Intent myIntent = new Intent(this, TestShortcutActivity.class); // 设置快捷方式的标题 addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title); // 设置快捷方式的图标 addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); // 设置快捷方式对应的Intent addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent); // 发送广播添加快捷方式 sendBroadcast(addIntent); // 把计数写入文件 editor.putInt("count", count); // 提交修改 editor.commit(); } } 权限: Activity配置: android:name="com.home.activity.TestShortcutActivity" android:label="@string/app_name" > |
CopyRight 2018-2019 实验室设备网 版权所有 |