Android如何跳過小米和魅族手機對Toast的限制
阿新 • • 發佈:2019-01-08
經常使用小米和魅族手機的小夥伴應該知道,他們兩者手機是可以把toast關閉掉的,這會讓使用者非常不爽,以至於我們很多提示只能用Dialog來實現,今天就告訴大傢伙怎麼跳過小米和魅族的限制,利用WindowManager來自定義我們自己的Toast就可以完美的跳過小米和魅族對Toast的限制。
自定義Toast程式碼如下:
public class Toast {
private Context mContext;
private WindowManager wm;
private int mDuration;
private View mNextView;
public static final int LENGTH_SHORT = 1500;
public static final int LENGTH_LONG = 3000;
public Toast(Context context) {
mContext = context.getApplicationContext();
}
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater) context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(R.layout.transient_notification, null );
TextView tv = (TextView) v.findViewById(R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
public static Toast makeText(Context context, int resId, int duration) throws Resources.NotFoundException {
return makeText(context, context.getResources().getText(resId), duration);
}
public void show() {
if (mNextView != null) {
wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = R.style.Animation_Toast;
params.y = dip2px(mContext, 64);
params.type = WindowManager.LayoutParams.TYPE_TOAST;
wm.addView(mNextView, params);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (mNextView != null) {
//每次顯示完後,remove調view
wm.removeView(mNextView);
mNextView = null;
wm = null;
}
}
}, mDuration);
}
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
上面最重要的一句就是:WindowManager.LayoutParams.TYPE_TOAST; 設定WindowManager的型別為TYPE_TOAST型別。