解决Android 7.1系统报错
通过反射注入在发生异常的地方进行try catch
package com.ding.basic.util;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.widget.Toast;
import com.ding.basic.Config;
import com.ding.basic.constants.C;
import java.lang.reflect.Field;
/**
* 解决Android 7.1系统报错
* 通过反射注入在发生异常的地方进行try catch
*/
public class ToastUtils {
private static ToastmToast;
private static FieldsField_TN;
private static FieldsField_TN_Handler;
static {
try {
sField_TN = Toast.class.getDeclaredField("mTN");
sField_TN.setAccessible(true);
sField_TN_Handler =sField_TN.getType().getDeclaredField("mHandler");
sField_TN_Handler.setAccessible(true);
}catch (Exception e) {
}
}
private static void hook(Toast toast) {
try {
Object tn =sField_TN.get(toast);
Handler preHandler = (Handler)sField_TN_Handler.get(tn);
sField_TN_Handler.set(tn, new SafelyHandlerWarpper(preHandler));
}catch (Exception e) {
}
}
public static void showToastNoRepeat(String text) {
try {
if (mToast ==null) {
mToast = Toast.makeText(Config.getContext(), text, Toast.LENGTH_SHORT);
}else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
hook(mToast);
}
mToast.show();
}catch (Exception e) {
e.printStackTrace();
}
}
public static void showDebugToastNoRepeat(String text) {
if (C.DEVELOP) {
if (mToast ==null) {
mToast = Toast.makeText(Config.getContext(), text, Toast.LENGTH_SHORT);
}else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
}
mToast.show();
}
}
/**
* 显示自定义布局Toast
*/
public static void showCustomToast(Context context, @LayoutRes int layoutResId, int gravity, String message, int duration) {
Toast toast =new Toast(context);
TextView view = (TextView) LayoutInflater.from(context).inflate(layoutResId, null, false);
toast.setView(view);
view.setText(message);
toast.setGravity(gravity, 0, 0);
toast.setDuration(duration);
toast.show();
}
public static class SafelyHandlerWarpperextends Handler {
private Handlerimpl;
public SafelyHandlerWarpper(Handler impl) {
this.impl = impl;
}
@Override
public void dispatchMessage(Message msg) {
try {
super.dispatchMessage(msg);
}catch (Exception e) {
}
}
@Override
public void handleMessage(Message msg) {
impl.handleMessage(msg);//需要委托给原Handler执行
}
}
}
网友评论