wossoneri
9/23/2019 - 6:16 AM

blink float window

private Handler.Callback changeImageCallback = new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == 0) {
            changeColorIndex++;
            if (changeColorIndex >= 6) {
                changeColorIndex = 0;
            }
            if (changeColorIndex % 2 == 1) {
                blinkImageView.setBackgroundColor(Color.DKGRAY);
            } else {
                blinkImageView.setBackgroundColor(Color.BLACK);
            }
            animHandler.sendEmptyMessageDelayed(0, 1000);
        }
        return false;
    }
};

private void createWindow() {
    // 获取WindowManager服务
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    // 新建悬浮窗控件
    blinkImageView = new ImageView(getApplicationContext());
    blinkImageView.setBackgroundColor(Color.DKGRAY);

    // 设置LayoutParam
    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
    layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
    layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
    layoutParams.format = PixelFormat.RGBA_8888;
    layoutParams.width = 1;
    layoutParams.height = 1;
    layoutParams.x = 0;
    layoutParams.y = 0;
    layoutParams.gravity = Gravity.START | Gravity.TOP;

    // 将悬浮窗控件添加到WindowManager
    windowManager.addView(blinkImageView, layoutParams);
    animHandler = new Handler(getMainLooper(), changeImageCallback);
    animHandler.sendEmptyMessageDelayed(0, 1000);
}