インストールされているアプリケーションのホームショートカットをプログラマビリティで作成しようとしています。他のパッケージアクティビティ用のshorcutを作成する最適な方法
唯一の事私は、アプリケーション名、のは、例えば電卓com.android.calculator2
(1.5)を言わせてしまう可能な持っているであろうと考えます。
私は、現在のコード怒鳴るを使用しています、ショートカットが正常に作成されますが、活動はショートカット(私は推測間違ったアクティビティクラス名)から起動することはできませんし、また、時にはアイコンが壊れているようです。
またmanifest.xml
にcom.android.launcher.permission.INSTALL_SHORTCUT
を追加します。
はこれを達成するための最適な方法はありますか?
String appName = "com.android.calculator2";
Context newAppContext = null;
// Get other package context
try {
newAppContext =
context.createPackageContext(appName, Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
// Create shortcut
if(newAppContext != null) {
// Get Application Name
PackageManager pm = context.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(appName, 0);
} catch (final NameNotFoundException e) {
ai = null;
}
// Get application label
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
// Shortcut intent
Intent shortcutIntent = new Intent (Intent.ACTION_MAIN);
/** Problem in here **
shortcutIntent.setClassName(newAppContext, newAppContext.getClass().getName());
*********************/
shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Create intent
final Intent putShortCutIntent = new Intent();
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, applicationName);
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(newAppContext,
R.drawable.icon));
putShortCutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
// Broadcast intent
context.sendBroadcast(putShortCutIntent);
}
EDIT: PackageManager.getLaunchIntentForPackage(文字列のpackageName)からテントを取得することによって、これを達成するために管理
。だから、
:それはパッケージ内のメインアクティビティクラスを見つけることができないとき
// Intent shortcutIntent = new Intent (Intent.ACTION_MAIN);
// shortcutIntent.setClassName(newAppContext, newAppContext.getClass().getName());
// shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent shorcutIntent = pm.getLaunchIntentForPackage(appName);
ありがとう@LAS_VEGASを、私はそれを理解しています。しかし、アクティビティ名を動的に取得する方法と、ハードコードしない方法が不思議でした。 "com.android.calculator2"というパッケージ名しか持たないことを考慮すると、PackageManagerを使用してApplicationInfoを取得できますが、パッケージのデフォルトのActivity名を取得できませんでした。 –
@ルイス私の編集を参照 – Caner
もう一度@LAS_VEGASさん、あなたの提案を試してみてください。作成したショートカットは、ショートカットを開くアプリケーションダイアログを呼び出します、多分私は正しく自分自身を説明していませんでした:) まあ、それにもかかわらず、私はPackageManagerからテントを得る代わりに、手動で1を定義することによって、望んでいた何をするために管理しました。 私はどんな方法でショートカットを変更するつもりはないので、うまく動作します。そのままホーム画面に追加してください。 インテントshortcutIntent = pm.getLaunchIntentForPackage(appName); –