[Android]指定されたアプリケーションのデスクトップショートカットを作成します.
3041 ワード
転載先:http://blog.csdn.net/sodino/article/details/6624521
インターネット検索では、自分のアプリケーションのためのショートカットを作成しますが、ここでは「指定されたアプリケーション」のためのデスクトップショートカットを作成することに重点を置いています.一般的なデスクトップショートカットには2つの要素があります.1.アプリケーション名2.アプリケーションアイコン.
アプリケーションのアイコンを指定する情報は以下の通りです.
インターネット検索では、自分のアプリケーションのためのショートカットを作成しますが、ここでは「指定されたアプリケーション」のためのデスクトップショートカットを作成することに重点を置いています.一般的なデスクトップショートカットには2つの要素があります.1.アプリケーション名2.アプリケーションアイコン.
アプリケーションのアイコンを指定する情報は以下の通りです.
// pkgContext ,iconIdentifier ,
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext,
iconIdentifier);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
サードパーティアプリケーションを作成するショートカットは、サードパーティアプリケーションのコンテキスト環境をどのように取得するかがポイントです.キーコードは以下の通りです. Context pkgContext = context.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY
| Context.CONTEXT_INCLUDE_CODE);
OKです.基礎知識は終わりました.直接コードを読者に提供します. /**
* @param context
* 。
* @params pkg , null。
* @return true ,<br/>
* false pkg null Launch MainActivity 。
* @author sodino
* */
public boolean addShortcut(Context context, String pkg) {
//
String title = "unknown";
// MainActivity
String mainAct = null;
//
int iconIdentifier = 0;
// MainActivity
PackageManager pkgMag = context.getPackageManager();
Intent queryIntent = new Intent(Intent.ACTION_MAIN, null);
queryIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> list = pkgMag.queryIntentActivities(queryIntent,
PackageManager.GET_ACTIVITIES);
for (int i = 0; i < list.size(); i++) {
ResolveInfo info = list.get(i);
if (info.activityInfo.packageName.equals(pkg)) {
title = info.loadLabel(pkgMag).toString();
mainAct = info.activityInfo.name;
iconIdentifier = info.activityInfo.applicationInfo.icon;
break;
}
}
if (mainAct == null) {
//
return false;
}
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
//
// shortcut.putExtra("duplicate", false);
ComponentName comp = new ComponentName(pkg, mainAct);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
new Intent(Intent.ACTION_MAIN).setComponent(comp));
//
Context pkgContext = null;
if (context.getPackageName().equals(pkg)) {
pkgContext = context;
} else {
// , 。
try {
pkgContext = context.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY
| Context.CONTEXT_INCLUDE_CODE);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
if (pkgContext != null) {
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext,
iconIdentifier);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
}
// ,
// <uses-permission
// android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
context.sendBroadcast(shortcut);
return true;
}