Skip to content

Instantly share code, notes, and snippets.

@soulduse
Created August 25, 2019 06:12
Show Gist options
  • Save soulduse/e92f771fc9f6f705ee574aff6af9b56f to your computer and use it in GitHub Desktop.
Save soulduse/e92f771fc9f6f705ee574aff6af9b56f to your computer and use it in GitHub Desktop.
Open app or go to the google play store market in Android with Kotlin
// 앱이 설치 설치되었는지 판단하는 함수
fun Context.isInstalledApp(packageName: String): Boolean {
val intent = packageManager.getLaunchIntentForPackage(packageName)
return intent != null
}
// 특정 앱을 실행하는 함수
fun Context.openApp(packageName: String) {
val intent = packageManager.getLaunchIntentForPackage(packageName)
startActivity(intent)
}
// 마켓으로 이동하는 함수
fun Context.market(packageName: String): Boolean {
return try {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("market://details?id=$packageName")
startActivity(intent)
true
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
false
}
}
// Usage
class ExampleActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
openAppOrGotoMarket()
}
private fun openAppOrGotoMarket() {
if (isInstalledApp(PACKAGE_NAME)) { // 내가 실행하고자 하는 앱이 있는가?
openApp(PACKAGE_NAME)
return
}
market(PACKAGE_NAME) // 없으면 마켓으로 보낸다.
}
companion object {
private const val PACKAGE_NAME = "com.soulduse.app.example"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment