Android/ショートカット作成
提供: 初心者エンジニアの簡易メモ
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
/**
* ショートカット作成ユーティリティ
* 必須:<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
*/
public class ShortcutUtil {
private Context mContext;
public ShortcutUtil(Context context)
{
mContext = context;
}
/**
* ショートカット作成(urlをひもづける
* @ex
* ShortcutUtil.makeShortcutUrl(getApplicationContext(), R.drawable.ic_launcher, getApplicationContext().getResources().getString(R.string.app_name), "http://google.com");
*/
public static void makeShortcutUrl(Context context, int icon, String name, String url)
{
Intent shortcut = new Intent(Intent.ACTION_VIEW);
shortcut.setData(Uri.parse(url));
ShortcutUtil.makeShortcutCore(context, icon, name, shortcut);
}
/**
* ショートカット作成(activityにひもづける
* @ex
* ShortcutUtil.makeShortcutActivity(getApplicationContext(), R.drawable.ic_launcher, getApplicationContext().getResources().getString(R.string.app_name), getPackageName() + ".SettingActivity");
*/
public static void makeShortcutActivity(Context context, int icon, String name, String className)
{
Intent shortcut = new Intent(Intent.ACTION_VIEW);
shortcut.setClassName(context, className);//getPackageName() + ".SearchActivity");
ShortcutUtil.makeShortcutCore(context, icon, name, shortcut);
}
/**
* ショートカット作成(コア処理
*/
private static void makeShortcutCore(Context context, int icon, String name, Intent shortcut)
{
Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
intent.putExtra("duplicate", false); //ショートカットの再作成防止("ショートカットを作成しました","すでにショートカットがあります"のメッセージがシステムがはく
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, icon));
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
context.sendBroadcast(intent);
}
}
注意:すべてのホームアプリに追加されるので、1つでも空きスペースがないホームアプリがあると、”空きスペースがありません”とToastで表示される。
