-- Android

앱 단축아이콘과 웹사이트 단축아이콘 생성

어린왕자악꿍 2015. 5. 14. 11:08
앱 단축아이콘에 대해 생성 및 삭제하는 코드들은 웹사이트 상에 많이 존재한다.
그런데 웹사이트를 단축아이콘으로 만드는 것은 (북마크처럼) 많이 보이지 않아 아래와 같이 정리해둔다.
물론 실무에서 써 먹기 위해서는 두 단축아이콘 다 이미 처리되어 있는지 확인하는 로직이 필요하다.

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

먼저 INSTALL_SHORTCUT 권한을 추가한다.

// 앱 단축아이콘이 추가되며, 클릭하면 앱이 실행된다.
createAppShortcut(this, "APP");

// 웹사이트 단축아이콘이 추가되며, 클릭하면 Explorer 로 네이버사이트가 오픈된다.
createWebsiteShortcut(this, "http://www.naver.com", "네이버");

public void createAppShortcut(Context context, String name) {

     Intent shortcutIntent = new Intent();
     shortcutIntent.setAction(Intent.ACTION_MAIN);
     shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
     shortcutIntent.setClassName(context, getClass().getName());
     shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

     Intent intent = new Intent();
     intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
     intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
     intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_launcher));
     intent.putExtra("duplicate", false);

     intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
     sendBroadcast(intent);
}

public void createWebsiteShortcut(Context context, String urlStr, String name) {

     Intent shortcutIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlStr));

     Intent intent = new Intent();
     intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
     intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
     intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_launcher));
     intent.putExtra("duplicate", false);

     intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
     context.sendBroadcast(intent);
}