具体问题可以查看 https://www.jianshu.com/p/ccfc5fa3130c
说一下我得解决方式
当 Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1时自定义一个toast
然后通过反射,替换并代理handler,添加try catch保护
try { if (sTnField == null) { sTnField = Toast.class.getDeclaredField("mTN"); sTnField.setAccessible(true); } // get mTN instance in Toast Object mTN = sTnField.get(this); if (mTN != null && sTnHandlerField == null) { sTnHandlerField = mTN.getClass().getDeclaredField("mHandler"); sTnHandlerField.setAccessible(true); } // get mHandler member in Toast$TN if (sTnHandlerField != null) { Handler mHandler = (Handler) sTnHandlerField.get(mTN); // replace mHandler to our wrapped HackyHandler sTnHandlerField.set(mTN, new HackyHandler(mHandler)); } } catch (Exception e) { ExceptionUtils.printStackTrace(e); }
并可以自己重写maketext
public static Toast makeText(Context context, CharSequence text, int duration) { Toast result = new MyToast(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final Resources resources = context.getResources(); View v = inflater.inflate(resources.getIdentifier("transient_notification", "layout", "android") /*com.android.internal.R.layout.transient_notification*/, null); TextView tv = (TextView) v.findViewById(resources.getIdentifier("message", "id", "android") /*com.android.internal.R.layout.transient_notification*/, null); tv.setText(text); result.setView(v); result.setDuration(duration); return result; }