Следующий код относится к образцу офиса с оплатой через приложение Google код .
Мне нужно протестировать его на реальном мобильном телефоне, потому что тестировать Google в приложении сложно. оплата в Android эмуляторе Studio.
К сожалению, приложение вылетало в реальном мобильном телефоне, когда я открываю FragmentBuy
, я почти не получаю информацию об ошибке sh.
Я снова проверил свой код и снова, я гость, есть два места, которые вызывают cra sh, одно - private fun processPurchases(purchasesResult: Set<Purchase>)
, другое - private fun acknowledgeNonConsumablePurchasesAsync(nonConsumables: List<Purchase>)
.
1: они помещают Toast.makeTex
в асинхронный поток , это причина cra sh?
2: Какой из них правильный между Billing.getInstance(requireActivity(), getString(R.string.skuRegisterApp))
и Billing.getInstance(requireContext), getString(R.string.skuRegisterApp))
?
3: Есть ли другие проблемы с моим кодом?
FragmentBuy.kt
class FragmentBuy : Fragment() {
private lateinit var binding: LayoutBuyBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(
inflater, R.layout.layout_buy, container, false
)
val mBilling=Billing.getInstance(requireActivity(), getString(R.string.skuRegisterApp)) // or Billing.getInstance(requireContext), getString(R.string.skuRegisterApp))
mBilling.initBillingClient()
binding.btnPurchase.setOnClickListener {
mBilling.purchaseProduct(requireActivity())
}
return binding.root
}
}
fun Context.toast(msg: String){
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
fun Fragment.toast(@StringRes resId: Int) {
toast(requireContext().getString(resId))
}
Billing.kt
class Billing private constructor (private val mContext: Context, private val purchaseItem :String)
:PurchasesUpdatedListener, BillingClientStateListener {
private lateinit var playStoreBillingClient: BillingClient
private val mapSkuDetails = mutableMapOf<String,SkuDetails>()
fun initBillingClient() {
playStoreBillingClient = BillingClient
.newBuilder(mContext)
.enablePendingPurchases() // required or app will crash
.setListener(this)
.build()
if (!playStoreBillingClient.isReady) {
playStoreBillingClient.startConnection(this)
}
}
override fun onBillingSetupFinished(billingResult: BillingResult) {
when (billingResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
querySkuDetailsAsync(BillingClient.SkuType.INAPP, listOf(purchaseItem) )
queryAndProcessPurchasesAsync()
mContext.toast(R.string.msgBillINIOK)
}
...
}
}
private fun querySkuDetailsAsync(@BillingClient.SkuType skuType: String, skuList: List<String>) {
val params = SkuDetailsParams.newBuilder().setSkusList(skuList).setType(skuType).build()
playStoreBillingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
when (billingResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
if (skuDetailsList.orEmpty().isNotEmpty()) {
skuDetailsList?.forEach {
mapSkuDetails.put(it.sku,it)
}
}
}
'''
}
}
}
private fun queryAndProcessPurchasesAsync() {
val purchasesResult = HashSet<Purchase>()
var result = playStoreBillingClient.queryPurchases(BillingClient.SkuType.INAPP)
result?.purchasesList?.apply { purchasesResult.addAll(this) }
processPurchases(purchasesResult)
}
private fun processPurchases(purchasesResult: Set<Purchase>): Job {
return CoroutineScope(Job() + Dispatchers.IO).launch {
val validPurchases = HashSet<Purchase>(purchasesResult.size)
purchasesResult.forEach { purchase ->
if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {
if (purchase.sku.equals(purchaseItem)) {
if (isSignatureValid(purchase)) {
validPurchases.add(purchase)
setIsRegisteredAppAsTrue(mContext)
mContext.toast(R.string.msgOrderOK) //Will it be crash?
}
}
}
...
}
acknowledgeNonConsumablePurchasesAsync(validPurchases.toList())
}
}
private fun acknowledgeNonConsumablePurchasesAsync(nonConsumables: List<Purchase>) {
nonConsumables.forEach { purchase ->
val params = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase
.purchaseToken).build()
playStoreBillingClient.acknowledgePurchase(params) { billingResult ->
when (billingResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
mContext.toast(R.string.msgOrderAcknowledgeOK) //Will it be crash?
}
else -> mContext.toast(R.string.msgOrderAcknowledgeError, billingResult.debugMessage)
}
}
}
}
//执行playStoreBillingClient.launchBillingFlow(...)后 launch
override fun onPurchasesUpdated(billingResult: BillingResult, purchases: MutableList<Purchase>?) {
when (billingResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
purchases?.apply { processPurchases(this.toSet()) }
}
...
}
}
fun purchaseProduct(activity: Activity) {
val skuDetails = mapSkuDetails[purchaseItem]
skuDetails?.let{
val purchaseParams = BillingFlowParams.newBuilder().setSkuDetails(skuDetails).build()
playStoreBillingClient.launchBillingFlow(activity, purchaseParams)
}
}
companion object {
private const val LOG_TAG = "BillingRepository"
private var INSTANCE: Billing? = null
fun getInstance(mContext: Context, purchaseItem: String): Billing =
INSTANCE ?: synchronized(this) {
INSTANCE ?: Billing(mContext, purchaseItem).also { INSTANCE = it }
}
}
}