Android(安卓)7.1.1 Toast引起的Crash
Android 7.1.1 Toast引起的Crash
背景
最近一直做国际化项目,用户使用的手机都是android中低档手机,出现的问题也比较奇葩,最近项目刚上线就遇到了一个crash
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@bf0c2d7 is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:797) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:351) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) at android.widget.Toast$TN.handleShow(Toast.java:465) at android.widget.Toast$TN$2.handleMessage(Toast.java:347) at android.os.Handler.dispatchMessage(Handler.java:110) at android.os.Looper.loop(Looper.java:203) at android.app.ActivityThread.main(ActivityThread.java:6337) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1084)
初步分析
最开始我以为是dialog或者popwindow引起的问题,我还找相关同事排查了一下,发现不是,通过log堆栈分析是Toast引起的问题,这个奇怪了,这个项目的代码之前一直在国内运行,一直没有发现过这个问题,如果是项目中Toast使用问题应该早就发现了??
搜索相关资料
在网上找了写相关资料,也有不少网友遇到类似的问题,问题都是集中在Android7.1.1和Android7.1.2机型上,出问题的机型正好是Android7.1.1手机!先看看到底是什么原因引起的吧
Android7.1.1出现问题的原因
先来看看前辈的解答吧
答案.png
总结一下,这个问题可以算是android 系统为了优化系统,才引起了bug,好在8.0的系统上已经发现这个问题已经try-catch修复了,最起码不导致崩溃了
截取了一段Toast的源代码(Android8.0 的源码),已经处理了
public void handleShow(IBinder windowToken) { if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView + " mNextView=" + mNextView); // If a cancel/hide is pending - no need to show - at this point // the window token is already invalid and no need to do any work. if (mHandler.hasMessages(CANCEL) || mHandler.hasMessages(HIDE)) { return; } if (mView != mNextView) { // remove the old view if necessary handleHide(); mView = mNextView; Context context = mView.getContext().getApplicationContext(); String packageName = mView.getContext().getOpPackageName(); if (context == null) { context = mView.getContext(); } mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); // We can resolve the Gravity here by using the Locale for getting // the layout direction final Configuration config = mView.getContext().getResources().getConfiguration(); final int gravity = Gravity.getAbsoluteGravity(mGravity, config.getLayoutDirection()); mParams.gravity = gravity; if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) { mParams.horizontalWeight = 1.0f; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) { mParams.verticalWeight = 1.0f; } mParams.x = mX; mParams.y = mY; mParams.verticalMargin = mVerticalMargin; mParams.horizontalMargin = mHorizontalMargin; mParams.packageName = packageName; mParams.hideTimeoutMilliseconds = mDuration == Toast.LENGTH_LONG ? LONG_DURATION_TIMEOUT : SHORT_DURATION_TIMEOUT; mParams.token = windowToken; if (mView.getParent() != null) { if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this); mWM.removeView(mView); } if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this); // Since the notification manager service cancels the token right // after it notifies us to cancel the toast there is an inherent // race and we may attempt to add a window after the token has been // invalidated. Let us hedge against that. try { mWM.addView(mView, mParams); trySendAccessibilityEvent(); } catch (WindowManager.BadTokenException e) { /* ignore */ //关键的地方,已经catch住了 } } }
如果要从根本上解决这类问题还是比较难的,因为要排查系统中哪些地方导致 了主线程阻塞住了,但是如果直接解决这个崩溃问题还是比较简单的
解决方案
网上有一个解决这个问题的[开源库]https://github.com/drakeet/ToastCompat)
思路:
So I created this library, and replace the base Context to a SafeToastContext, it will hook the WindowManagerWrapper.addView(view, params) method and fix the exception.
实际上就是Hook住了系统WindowManager的addview方法,对这个方式try-catch处理了
文件分析:主要就三个文件
文件目录.png使用方式
import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.widget.Toast;import me.drakeet.support.toast.ToastCompat;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ToastCompat.makeText(this, "hello", Toast.LENGTH_SHORT) .setBadTokenListener(toast -> { Log.e("failed toast", "hello"); }).show(); }}
对弹出Toast地方,都使用统一的ToastCompat方式,我们看一下ToastCompat是什么吧?
ToastCompat就是对Toast的代理也可以称之为委托,先看一下关键方法makeText
public static ToastCompat makeText(Context context, CharSequence text, int duration) { // We cannot pass the SafeToastContext to Toast.makeText() because // the View will unwrap the base context and we are in vain. @SuppressLint("ShowToast") Toast toast = Toast.makeText(context, text, duration); setContextCompat(toast.getView(), new SafeToastContext(context, toast)); return new ToastCompat(context, toast); }
首先创建了一个Toast对象,然后又调用了setContextCompat方法
private static void setContextCompat(@NonNull View view, @NonNull Context context) { if (Build.VERSION.SDK_INT == 25) { try { Field field = View.class.getDeclaredField("mContext"); field.setAccessible(true); field.set(view, context); } catch (Throwable throwable) { throwable.printStackTrace(); } } }
把ToastView context 给替换了
final class SafeToastContext extends ContextWrapper { private @NonNull Toast toast; private @Nullable BadTokenListener badTokenListener; SafeToastContext(@NonNull Context base, @NonNull Toast toast) { super(base); this.toast = toast; } @Override public Context getApplicationContext() { return new ApplicationContextWrapper(getBaseContext().getApplicationContext()); } public void setBadTokenListener(@NonNull BadTokenListener badTokenListener) { this.badTokenListener = badTokenListener; }
关键的是getApplicationContext 这个方法
private final class ApplicationContextWrapper extends ContextWrapper { private ApplicationContextWrapper(@NonNull Context base) { super(base); } @Override public Object getSystemService(@NonNull String name) { if (Context.WINDOW_SERVICE.equals(name)) { // noinspection ConstantConditions return new WindowManagerWrapper((WindowManager) getBaseContext().getSystemService(name)); } return super.getSystemService(name); } }
实际上在获取系统中WindowManager的时候,是获取了我们包装类的
WindowManagerWrapper,在这个类中我们对addView 增加了try-catch的操作
private final class WindowManagerWrapper implements WindowManager { private static final String TAG = "WindowManagerWrapper"; private final @NonNull WindowManager base; private WindowManagerWrapper(@NonNull WindowManager base) { this.base = base; } @Override public Display getDefaultDisplay() { return base.getDefaultDisplay(); } @Override public void removeViewImmediate(View view) { base.removeViewImmediate(view); } @Override public void addView(View view, ViewGroup.LayoutParams params) { try { Log.d(TAG, "WindowManager's addView(view, params) has been hooked."); base.addView(view, params); } catch (BadTokenException e) { Log.i(TAG, e.getMessage()); if (badTokenListener != null) { badTokenListener.onBadTokenCaught(toast); } } catch (Throwable throwable) { Log.e(TAG, "[addView]", throwable); } } @Override public void updateViewLayout(View view, ViewGroup.LayoutParams params) { base.updateViewLayout(view, params); } @Override public void removeView(View view) { base.removeView(view); } }
总结:代码并不复杂,逻辑比较清晰,实现的思路也是比较有趣的
疑问:
- Toast的实现原理是什么呢?
- ContextWrapper 是什么呢?
- ContextWrapper 中getApplicationContext 返回的是什么呢
为什么会有这些疑问,一般对疑难的crash问题我都喜欢刨根问底,探究问题根源对问题的执着会让你在过程中收获很多问题,以上问题就是我在专研这类问题的时候遇到的相关知识,有写知识之前都看过但是随着时间的流逝也都不记得了
引用
大家有没有遇到过只在 Android 7.1 机型上报告的由Toast引起的BadTokenException错误?
github 上解决方案
Toast与Snackbar的那点事
Android7.1.1Toast崩溃解决方案
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- Nginx系列教程(六)| 手把手教你搭建 LNMP 架构并部署天空网络电影
- 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
- Android改变手机屏幕朝向的方法
- Kotlin之Android项目实战--[玩android网站]App
- android Fragment 常用api方法
- 深入浅出 - Android系统移植与平台开发(十三) - Sensor HAL框架分
- Android(安卓)IntentService使用全面介绍及源码解析
- Build/Environmen