The accepted answer works well however, I thought it would be good to show you how I implemented the functionality in Kotlin and took care of different SDKs.
The gist is available at: https://gist.github.com/Hesamedin/3e0766a8ee743488e61c2386af6d6f69
The final result would be like this:
BrowserInformation: { AppName: Samsung Internet, Version: 1230101502,
PackageName: com.sec.android.app.sbrowser }
You can use this extension function in your Activity/Fragment.
private fun logBrowserInfo() {
val pair = this.getDefaultBrowserInfo()
val info = pair.first
val error = pair.second
}
Context Extension
fun Context?.getDefaultBrowserInfo(): Pair<String, Exception?> {
val ctx = this ?: return Pair("", null)
var browserInfo = ""
var error: Exception? = null
try {
val packageManager = ctx.packageManager
browserInfo = packageManager.defaultBrowserInfo()
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
error = e
}
return Pair(browserInfo, error)
}
private fun PackageManager.defaultBrowserInfo(): String {
val browserIntent = Intent("android.intent.action.VIEW", Uri.parse("http://"))
var appName = ""
var appVersion = ""
var packageName = ""
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val resolveInfo = resolveActivity(
browserIntent,
PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())
)
packageName += resolveInfo?.activityInfo?.packageName
appName += resolveInfo?.loadLabel(this)
val packageInfo = this.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
appVersion += getPackageVersion(packageInfo)
} else {
val resolveInfo = @Suppress("DEPRECATION") resolveActivity(
browserIntent,
PackageManager.MATCH_DEFAULT_ONLY
)
packageName += resolveInfo?.activityInfo?.packageName
val packageInfo = @Suppress("DEPRECATION") this.getPackageInfo(packageName, 0)
appVersion += getPackageVersion(packageInfo)
}
val sb = StringBuilder()
sb.append("BrowserInformation: { ")
sb.append("AppName: ").append(appName).append(", ")
sb.append("Version: ").append(appVersion).append(", ")
sb.append("PackageName: ").append(packageName)
sb.append(" }")
return sb.toString()
}
private fun getPackageVersion(packageInfo: PackageInfo): String {
try {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
packageInfo.longVersionCode.toString()
} else {
@Suppress("DEPRECATION") packageInfo.versionCode.toString()
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return "N/A"
}