getInstallerPackageName(字符串):字符串?'已弃用。在 Java 中已弃用

问题描述 投票:0回答:2

我写了一个简单的声明,如下所示:

val installer = context.packageManager.getInstallerPackageName(context.packageName)

但现在已弃用,如图所示:

是否有其他方法可以获取已安装您的应用程序的应用程序包名称?

android deprecated
2个回答
10
投票

以下是如何使用新的:

    fun getInstallerPackageName(context: Context, packageName: String): String? {
        kotlin.runCatching {
            if (VERSION.SDK_INT >= VERSION_CODES.R)
                return context.packageManager.getInstallSourceInfo(packageName).installingPackageName
            @Suppress("DEPRECATION")
            return context.packageManager.getInstallerPackageName(packageName)
        }
        return null
    }

0
投票

就我而言,

package you_package_name

import android.content.pm.PackageManager
import android.view.View
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactContext
import com.facebook.react.uimanager.ReactShadowNode
import com.facebook.react.uimanager.ViewManager
import android.util.Log
import android.os.Build
import android.content.Context

class InstallerCheckerModule(reactContext: ReactApplicationContext) : 
ReactContextBaseJavaModule(reactContext), ReactPackage {

override fun getName(): String {
    return "InstallerChecker"
}

// Function to check if the app was installed from Google Play Store
@ReactMethod
fun isInstalledFromGooglePlay(promise: Promise) {
    try {
        val installerPackageName = getInstallerPackageName(reactApplicationContext, reactApplicationContext.packageName)
        Log.d("InstallerChecker", "Installer package name: $installerPackageName")
        if (installerPackageName != null && installerPackageName == "com.android.vending") {
            promise.resolve(true) // App was installed from Google Play Store
        } else {
            promise.resolve(false) // App was not installed from Google Play Store
        }
    } catch (e: Exception) {
        promise.reject("ERROR", e.message)
    }
}

// Get the installer package name
private fun getInstallerPackageName(context: Context, packageName: String): String? {
    return kotlin.runCatching {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
            context.packageManager.getInstallSourceInfo(packageName).installingPackageName
        else
            @Suppress("DEPRECATION")
            context.packageManager.getInstallerPackageName(packageName)
    }.getOrNull()
}

override fun createNativeModules(p0: ReactApplicationContext): MutableList<NativeModule> {
    return mutableListOf()
}

override fun createViewManagers(p0: ReactApplicationContext): MutableList<ViewManager<View, ReactShadowNode<*>>> {
    return mutableListOf()
}
}
© www.soinside.com 2019 - 2024. All rights reserved.