您的位置:首页 > 移动开发 > Android开发

Android创建桌面快捷方式

2016-06-06 14:36 344 查看

Android创建桌面快捷方式

首先在MainActivity的onCreate调用以下方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!hasShortCut(this)) {
addShortCut();
}
}


hasShortCut(Context context)方法代码:

//判断桌面快捷方式是否存在!
public boolean hasShortCut(Context context) {
String url = "";
System.out.println(getSystemVersion());
//2.2以后的手机读取的路径与之前的不一样
if (getSystemVersion() < 8) {
url = "content://com.android.launcher.settings/favorites?notify=true";
} else {
url = "content://com.android.launcher2.settings/favorites?notify=true";
}
//获取内容提供器的实例
ContentResolver resolver = context.getContentResolver();
//通过游标查询是否已经存在该应用的快捷方式
Cursor cursor = resolver.query(Uri.parse(url), null, "title=?",
new String[] { context.getString(R.string.app_name) }, null);

if (cursor != null && cursor.moveToFirst()) {
cursor.close();
return true;//已经存在
}

return false;//不存在
}


获取系统版本号:

//获取当前系统使用的版本号
private int getSystemVersion() {
return android.os.Build.VERSION.SDK_INT;
}


*添加桌面快捷方式的代码:

// 添加快捷方式:
public void addShortCut() {
// 创建快捷方式的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.ic_launcher);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
// 点击快捷图片,运行的程序主入口,这里为自己启动自己
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
getApplicationContext(), MainActivity.class));
// 发送广播,通知桌面创建
sendBroadcast(shortcutintent);
}


需要的权限以及对应Activity的配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.createshortcut2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- 需要权限 -->
<!-- 读取桌面快捷方式是否存在的权限 -->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
<!-- 添加桌面快捷方式需要的权限 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.createshortcut2.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" >
</action>
</intent-filter>
</activity>
</application>

</manifest>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  桌面快捷方式