Kotlin:packageManager.getLaunchIntentForPackage()无法启动应用程序

u7up0aaq  于 2023-03-24  发布在  Kotlin
关注(0)|答案(2)|浏览(275)

Kotlinapps是这样的:

package com.test.openchrome

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val launcher = findViewById<Button>(R.id.openchrome)
        launcher.setOnClickListener{
            var launchIntent: Intent? = null
            try {
                launchIntent = packageManager.getLaunchIntentForPackage("com.android.chrome")
            } catch (ignored: Exception) {
            }

            if (launchIntent == null) {
                startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "com.android.chrome")))
            } else {
                startActivity(launchIntent)
            }
        }
    }
}

我在我的Android上安装了Chrome。
但是当我按下“打开chrome”按钮时,chrome没有打开。而是切换到playstore。

5q4ezhmt

5q4ezhmt1#

试试这个

try {
 launchIntent =packageManager.getLaunchIntentForPackage("com.android.chrome")
 startActivity(launchIntent)
} catch (E: Exception) {
  println("Package not found")
}
avwztpqn

avwztpqn2#

您需要转到AndroidManifest.xml并添加

<queries>
    <package android:name="com.android.chrome" />

</queries>

在你的代码中,
var launchIntent = packageManager.getLaunchIntentForPackage(“com.android.chrome“)startActivity(launchIntent)
就这样!

相关问题