第一次运行程序添加快捷方式,我是在SharedPreferences里面添加了一个字段标记是不是第一次运行。
我在Application的实现类的onCreate方法中判断
@Override
public void onCreate() {
super.onCreate();
appContext = getApplicationContext();
SharedPreferences shortcutpref = appContext.getSharedPreferences(
"shortcut", Context.MODE_PRIVATE);
boolean iscreated = shortcutpref.getBoolean("iscreated", false);
if (!iscreated) {
createDeskShortCut();
}
下面就是createDeskShortCut的实现:
/**
* 创建快捷方式
*/
public void createDeskShortCut() {
// 创建快捷方式的Intent
Intent shortcutIntent = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 不允许重复创建
shortcutIntent.putExtra("duplicate", false);
// 需要显示的名称
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getString(R.string.app_name));
// 快捷图片
Parcelable icon = Intent.ShortcutIconResource.fromContext(
getApplicationContext(), R.drawable.logo);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
Intent intent = new Intent(getApplicationContext(),
WelcomeActivity.class);
// 下面两个属性是为了当应用程序卸载时桌面 上的快捷方式会删除
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
// 点击快捷图片,运行的程序主入口
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// 发送广播。OK
sendBroadcast(shortcutIntent);
// 在配置文件中声明已经创建了快捷方式
appContext.getSharedPreferences("shortcut", Context.MODE_PRIVATE)
.edit().putBoolean("iscreated", true).commit();
// 2.3.3系统创建快捷方式不提示
if (android.os.Build.VERSION.SDK.equals("10")) {
Toast.makeText(
appContext,
"已创建"
+ appContext.getResources().getString(
R.string.app_name) + "快捷方式。",
Toast.LENGTH_LONG).show();
}
String handSetInfo = "手机型号:" + android.os.Build.MODEL + ",SDK版本:"
+ android.os.Build.VERSION.SDK + ",系统版本:"
+ android.os.Build.VERSION.RELEASE;
Log.e("HANDINFO", handSetInfo);
}
这种方法我测试了4.0以上的都没有问题,都是可以Toast提示创建的,但是用2.3.3运行的时候 快捷方式创建了,但是没有提示。
创建快捷方式是发一个广播,然后由系统为您创建,创建成功会自动提示,但是可能有兼容问题导致2.3.3没有提示。这里就手动添加以下了。
上面获取SDK版本 和 系统版本都是很常用的,记录以下:
"手机型号:" android.os.Build.MODEL
"SDK版本:" android.os.Build.VERSION.SDK
"系统版本:" android.os.Build.VERSION.RELEASE