Toast.makeText 当我在 Android Studio 的异步线程中调用它时会导致应用程序崩溃吗?
Will Toast.makeText cause app crash when I invoke it in asynchronous thread in Android Studio?
以下代码是关于Google基于应用内支付的办公示例code。
我必须在真实的移动设备中测试它 phone 因为很难在 Android Studio 模拟器中测试 Google 应用内支付。
不幸的是,当我打开 FragmentBuy
时,该应用程序在真实移动设备 phone 中崩溃了,我几乎没有得到有关崩溃的错误信息。
我再次检查了我的代码,我猜有两个地方导致崩溃,一个是 private fun processPurchases(purchasesResult: Set<Purchase>)
,另一个是 private fun acknowledgeNonConsumablePurchasesAsync(nonConsumables: List<Purchase>)
.
1:他们在异步线程中启动Toast.makeTex
,是崩溃的原因吗?
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 }
}
}
}
要显示 Toast
你的 Thread
必须有 MessageQueue
,在这种情况下,我建议你使用 Activity
而不是 Context
并使用方法 runOnUiThread
mActivity.runOnUiThread {
// show your Toast
}
对于任何界面更改,请调用 activity.runOnUiThread(runnable)
。
并使用 Kotlin 调用
activity.runOnUiThread{
toast("Your text") //since you are using extension function.
}
因为Toast
在源代码中被Handler
使用了。
private static class TN extends ITransientNotification.Stub {
TN(String packageName, @Nullable Looper looper) {
//There need the Looper first
if (looper == null) {
// Use Looper.myLooper() if looper is not specified.
looper = Looper.myLooper();
if (looper == null) {
throw new RuntimeException(
"Can't toast on a thread that has not called Looper.prepare()");
}
}
mHandler = new Handler(looper, null) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW: {
IBinder token = (IBinder) msg.obj;
handleShow(token);
break;
}
}
}
};
}
/**
* schedule handleShow into the right thread
*/
@Override
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
public void show(IBinder windowToken) {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
//the show is used Handler
mHandler.obtainMessage(SHOW, windowToken).sendToTarget();
}
}
这是Toast
源码中的TN
,之所以显示Toast
是Handler使用的,所以需要在Main Thread.If中使用需要在异步线程中使用Toast
,我们需要创建一个Looper.
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
Toast.makeText(MainActivity.this,"",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
- 是的。您只能显示来自 UI 主线程的 toast 消息。要从任何其他线程启动 toask 消息,您可以像这样使用 Hander:
new Handler(Looper.getMainLooper()).post(() -> {
Toast.makeText(someContext, "some toast", Toast.LENGTH_SHORT).show();
});
此外,您必须使用 activity 上下文,而不是片段上下文。
要从片段中获取 activity 上下文,您可以使用:
getActivity()
所以你可以在你的片段中做这样的事情:
new Handler(Looper.getMainLooper()).post(() -> {
Toast.makeText(getActivity(), "some toast", Toast.LENGTH_SHORT).show();
});
由于您使用的是扩展函数,因此需要将其更改为使用 activity 上下文:
fun Fragment.toast(@StringRes resId: Int) {
getActivity().toast(requireContext().getString(resId))
}
然后您可以在处理程序中使用 toast()(以从不同的线程显示它):
new Handler(Looper.getMainLooper()).post(() -> {
toast("some toast")
});
第一个更正确,但您应该在 activity 的上下文中使用 getString():
Billing.getInstance(requireActivity(),
getActivity().getString(R.string.skuRegisterApp))
其他一切似乎都很好
以下代码是关于Google基于应用内支付的办公示例code。
我必须在真实的移动设备中测试它 phone 因为很难在 Android Studio 模拟器中测试 Google 应用内支付。
不幸的是,当我打开 FragmentBuy
时,该应用程序在真实移动设备 phone 中崩溃了,我几乎没有得到有关崩溃的错误信息。
我再次检查了我的代码,我猜有两个地方导致崩溃,一个是 private fun processPurchases(purchasesResult: Set<Purchase>)
,另一个是 private fun acknowledgeNonConsumablePurchasesAsync(nonConsumables: List<Purchase>)
.
1:他们在异步线程中启动Toast.makeTex
,是崩溃的原因吗?
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 }
}
}
}
要显示 Toast
你的 Thread
必须有 MessageQueue
,在这种情况下,我建议你使用 Activity
而不是 Context
并使用方法 runOnUiThread
mActivity.runOnUiThread {
// show your Toast
}
对于任何界面更改,请调用 activity.runOnUiThread(runnable)
。
并使用 Kotlin 调用
activity.runOnUiThread{
toast("Your text") //since you are using extension function.
}
因为Toast
在源代码中被Handler
使用了。
private static class TN extends ITransientNotification.Stub {
TN(String packageName, @Nullable Looper looper) {
//There need the Looper first
if (looper == null) {
// Use Looper.myLooper() if looper is not specified.
looper = Looper.myLooper();
if (looper == null) {
throw new RuntimeException(
"Can't toast on a thread that has not called Looper.prepare()");
}
}
mHandler = new Handler(looper, null) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW: {
IBinder token = (IBinder) msg.obj;
handleShow(token);
break;
}
}
}
};
}
/**
* schedule handleShow into the right thread
*/
@Override
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
public void show(IBinder windowToken) {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
//the show is used Handler
mHandler.obtainMessage(SHOW, windowToken).sendToTarget();
}
}
这是Toast
源码中的TN
,之所以显示Toast
是Handler使用的,所以需要在Main Thread.If中使用需要在异步线程中使用Toast
,我们需要创建一个Looper.
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
Toast.makeText(MainActivity.this,"",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
- 是的。您只能显示来自 UI 主线程的 toast 消息。要从任何其他线程启动 toask 消息,您可以像这样使用 Hander:
new Handler(Looper.getMainLooper()).post(() -> { Toast.makeText(someContext, "some toast", Toast.LENGTH_SHORT).show(); });
此外,您必须使用 activity 上下文,而不是片段上下文。 要从片段中获取 activity 上下文,您可以使用:
getActivity()
所以你可以在你的片段中做这样的事情:
new Handler(Looper.getMainLooper()).post(() -> {
Toast.makeText(getActivity(), "some toast", Toast.LENGTH_SHORT).show();
});
由于您使用的是扩展函数,因此需要将其更改为使用 activity 上下文:
fun Fragment.toast(@StringRes resId: Int) {
getActivity().toast(requireContext().getString(resId))
}
然后您可以在处理程序中使用 toast()(以从不同的线程显示它):
new Handler(Looper.getMainLooper()).post(() -> { toast("some toast") });
第一个更正确,但您应该在 activity 的上下文中使用 getString():
Billing.getInstance(requireActivity(), getActivity().getString(R.string.skuRegisterApp))
其他一切似乎都很好