如何打印toast弹窗的文本?

文章描述了一个Android应用在运行时遇到的崩溃问题,原因是WindowManager$BadTokenException。为了定位具体是哪个Toast导致的问题,作者提供了一个解决方案,通过反射技术在AndroidP及以上版本解封非SDK接口,并创建动态代理来捕获和打印Toast的文本内容,以便于问题排查和修复。

背景

遇到app发生崩溃,如下图所示。无法定位到是哪个toast引发的问题。

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4cc8666 is not valid; is your activity running?
	at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
	at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
	at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
	at android.widget.Toast$TN.handleShow(Toast.java:502)
	at android.widget.Toast$TN$2.handleMessage(Toast.java:381)
	at android.os.Handler.dispatchMessage(Handler.java:102)
	at android.os.Looper.loop(Looper.java:154)
	at android.app.ActivityThread.main(ActivityThread.java:6267)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793)
Back traces end.

因此我们希望能打印出toast的弹窗文本内容。从而可以确定是app中哪一个toast引发。进而解决问题。

解决方案

前置依赖

Google官方在Android P(Android9.0版本)开始针对非 SDK 接口的限制。所以我们需要首先解除限制。比较有效的方案是
https://github.com/tiann/FreeReflection

可以在build.gradle里面添加依赖:
implementation ‘com.github.tiann:FreeReflection:3.1.0’

代码

import android.os.Build;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import me.weishu.reflection.Reflection;

public class ToastHook {
    private static final String TAG = ToastHook.class.getSimpleName();

    public static void hook(Context context) {
        Log.e(TAG, "hook");
        try {
            if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
                Log.e(TAG, "enter hook if...");
                boolean result = Reflection.unseal(context);
                if (!result) {
                    Log.e(TAG, "Failed to unseal");
                    return;
                }
                // 1,获取sService的Field
                Class<Toast> toastClass = Toast.class;
                Method getServiceMethod = toastClass.getDeclaredMethod("getService", null);
                getServiceMethod.setAccessible(true);
                final Object service = getServiceMethod.invoke(null);

                Field sServiceField = toastClass.getDeclaredField("sService");
                sServiceField.setAccessible(true);

                Class iNotificationManager = Class.forName("android.app.INotificationManager");
                // 2、动态代理替换
                Object proxy = Proxy.newProxyInstance(Thread.class.getClassLoader(), new Class[]{iNotificationManager}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (method.getName().equals("enqueueToast")) {
                            Log.e(TAG, method.getName());
                            getContent(args[1]);
                        }
                        return method.invoke(service, args);
                    }
                });
                // 用代理对象给sService赋值
                sServiceField.set(null, proxy);
            }
        } catch (Exception e) {

        }
    }

    private static void getContent(Object arg) {
        try {
            // 获取TN的class
            Class<?> tnClass = Class.forName(Toast.class.getName() + "$TN");
            if (tnClass == null) {
                return;
            }
            // 获取mNextView的Field
            Field mNextViewField = tnClass.getDeclaredField("mNextView");
            if (mNextViewField == null) {
                return;
            }
            mNextViewField.setAccessible(true);
            // 获取mNextView实例
            if (mNextViewField.get(arg) instanceof ViewGroup) {
                ViewGroup mNextView = (ViewGroup) mNextViewField.get(arg);
                // 获取textview
                TextView childView = null;
                int childCount = mNextView.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    if (mNextView.getChildAt(i) instanceof TextView) {
                        childView = (TextView) mNextView.getChildAt(i);
                    }
                }
                if (childView == null) {
                    Log.e(TAG, "childView == null:");
                    return;
                }
                // 获取文本内容
                CharSequence text = childView.getText();
                Log.e(TAG, "content: " + text);
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

后续

在application中,通过ToastHook.hook(this)。这样就可以以后一旦发生崩溃,在日志中就可以看到toast弹窗文本。继而进行有效的修复了。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值