天天看點

android 6.0 全局提示框,類似網吧包時結束時上方提示框

android 6.0 全局提示框,類似網吧包時結束時上方提示框

1.建立WindowManager

private static boolean isShow = true;
    private static WindowManager windowManager = null;
    private static MyMarqueeView marqueeView = null;
    private static WindowManager.LayoutParams params = null;
    
 private void createTipWindow() {
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        //擷取視窗布局參數執行個體
        params = new WindowManager.LayoutParams();
        //設定視窗布局參數屬性
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = 120;
        //設定window的顯示特性
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        //設定視窗半透明
        params.format = PixelFormat.TRANSLUCENT;
        params.gravity = Gravity.TOP;
        //設定視窗類型
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        marqueeView = new MyMarqueeView(this);
        marqueeView.setBackgroundColor(getResources().getColor(R.color.yellow));
    }
           

2.正常展示提示框

public void showTipWindow() {
        String timeStamp = PropertiesUtil.getTimeStamp(VLCApplication.getAppContext().getResources().getString(R.string.time_stamp));
        long currentT = System.currentTimeMillis();
        if (timeStamp != null && Long.decode(timeStamp) > 0) {
            Long surplusTime = Long.decode(timeStamp) - currentT;
            int surC = (int) (surplusTime / 60000);
            if (isShow && surC > 0) {
                isShow = false;
                if (!Settings.canDrawOverlays(VLCApplication.getAppContext()))
                    return;
                marqueeView.setContent("距離包時結束還剩下" + surC + "分鐘");
                windowManager.addView(marqueeView, params);
            }
        }
    }
           

3.銷毀提示框

這裡很容易發生錯誤 java.lang.IllegalArgumentException: View not attached to window manager

網上很多案例說是不讓使用removeView方法

,換成使用windowManager.removeViewImmediate(view);

然并卵。

public void hideTipWindow() {
        try {
            if (!isShow && marqueeView != null) {
                windowManager.removeView(marqueeView);
                isShow = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
           

我是把它放在service裡面去建立,沒有依附于activity,使用正常。

哦,對了,添權重限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

不能少了它。

然後在程式啟動時去申請權限

private  void requestAlertWindowPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
    }
           

在展示之前加判斷 if (! Settings.canDrawOverlays(this))

以免沒有權限報錯。

可能有人會問 MyMarqueeView 這個是什麼東西,這個是繼承textview做的一個自動橫向滾動提示語的一個view,如有需要,可留言告訴我哦。

到這裡系統提示框已經可以正常使用了,如果本文對你有一丢丢幫助。請幫忙點個贊,謝謝啦。

繼續閱讀