라떼군 이야기
안드로이드에서 홈 화면 바로가기 생성
Problem
안드로이드에서 앱 설치 후 바탕화면(런처)에 앱 아이콘을 표시하고자 한다.
Solution
Android 8 Oreo (API 26)이하에서는 다음 방법을 사용할 수 있다.
private fun addShortCut(context: Context) {
val shortcutIntent = Intent(Intent.ACTION_MAIN).apply {
addCategory(Intent.CATEGORY_LAUNCHER)
setClassName(context, javaClass.name)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
}
sendBroadcast(Intent().apply {
putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent)
putExtra(Intent.EXTRA_SHORTCUT_NAME, resources.getString(R.string.app_name))
putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.mipmap.ic_launcher))
putExtra("duplicate", false)
action = "com.android.launcher.action.INSTALL_SHORTCUT"
})
val editor = shortcutSharedPref?.edit()
editor?.putBoolean("isInstalled", true)
editor?.apply()
}
Android 8 Oreo (API 26)이상 부터는 broadcast 방식의 바탕화면 아이콘 생성을 지원하지 않기 때문에 ShortcutManagerCompat
를 이용한 다른 방법을 사용해야 한다.
if (ShortcutManagerCompat.isRequestPinShortcutSupported(this)) {
val shortcutInfo: ShortcutInfoCompat = ShortcutInfoCompat.Builder(this, "id")
.setIntent(Intent(this, MainActivity::class.java).setAction(Intent.ACTION_MAIN))
.setShortLabel(getString(R.string.app_name))
.setIcon(IconCompat.createWithResource(this, R.mipmap.ic_launcher))
.build()
ShortcutManagerCompat.requestPinShortcut(this, shortcutInfo, null)
}