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());
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 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);
}
<?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>