Android悬浮窗实现 使用WindowManager

WindowManager介绍

  通过Context.getSystemService(Context.WINDOW_SERVICE)可以获得 WindowManager对象。

  每一个WindowManager对象都和一个特定的 Display绑定。

  想要获取一个不同的display的WindowManager,可以用 createDisplayContext(Display)来获取那个display的 Context,之后再使用:

  Context.getSystemService(Context.WINDOW_SERVICE)来获取WindowManager。

  使用WindowManager可以在其他应用最上层,甚至手机桌面最上层显示窗口。

  调用的是WindowManager继承自基类的addView方法和removeView方法来显示和隐藏窗口。具体见后面的实例。

  另:API 17推出了Presentation,它将自动获取display的Context和WindowManager,可以方便地在另一个display上显示窗口。

WindowManager实现悬浮窗例子

声明权限

  首先在manifest中添加如下权限:

<!-- 显示顶层浮窗 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

  

  注意:在MIUI上需要在设置中打开本应用的”显示悬浮窗”开关,并且重启应用,否则悬浮窗只能显示在本应用界面内,不能显示在手机桌面上。

服务获取和基本参数设置

        // 获取应用的Context
mContext = context.getApplicationContext();
// 获取WindowManager
mWindowManager = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);

  参数设置:

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        // 类型
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT // 设置flag int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
// | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
// 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,弹出的View收不到Back键的事件
params.flags = flags;
// 不设置这个弹出框的透明遮罩显示为黑色
params.format = PixelFormat.TRANSLUCENT;
// FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
// 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时,后面的应用图标由不可长按变为可长按
// 不设置这个flag的话,home页的划屏会有问题 params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT; params.gravity = Gravity.CENTER;

点击和按键事件

  除了View中的各个控件的点击事件之外,弹窗View的消失控制需要一些处理。

  点击弹窗外部可隐藏弹窗的效果,首先,悬浮窗是全屏的,只不过最外层的是透明或者半透明的:

  布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@color/darken_background"
android:gravity="center"
android:orientation="vertical" > <RelativeLayout
android:id="@+id/popup_window"
android:layout_width="@dimen/dialog_window_width"
android:layout_height="@dimen/dialog_window_height"
android:background="@color/white"
android:orientation="vertical" > <TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="@dimen/dialog_title_height"
android:gravity="center"
android:text="@string/default_title"
android:textColor="@color/dialog_title_text_color"
android:textSize="@dimen/dialog_title_text_size" /> <View
android:id="@+id/title_divider"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="@id/title"
android:background="@drawable/dialog_title_divider" /> <TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/title_divider"
android:gravity="center"
android:padding="@dimen/dialog_content_padding_side"
android:text="@string/default_content"
android:textColor="@color/dialog_content_text_color"
android:textSize="@dimen/dialog_content_text_size" /> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:paddingBottom="@dimen/dialog_content_padding_bottom"
android:paddingLeft="@dimen/dialog_content_padding_side"
android:paddingRight="@dimen/dialog_content_padding_side" > <Button
android:id="@+id/negativeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/promote_window_negative_btn_selector"
android:focusable="true"
android:padding="@dimen/dialog_button_padding"
android:text="@string/default_btn_cancel"
android:textColor="@color/dialog_negative_btn_text_color"
android:textSize="@dimen/dialog_button_text_size" /> <Button
android:id="@+id/positiveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="18dp"
android:layout_weight="1"
android:background="@drawable/promote_window_positive_btn_selector"
android:focusable="true"
android:padding="@dimen/dialog_button_padding"
android:text="@string/default_btn_ok"
android:textColor="@color/dialog_positive_btn_text_color"
android:textSize="@dimen/dialog_button_text_size" />
</LinearLayout>
</RelativeLayout> </LinearLayout>

popupwindow.xml

  点击外部可消除设置:

        // 点击窗口外部区域可消除
// 这点的实现主要将悬浮窗设置为全屏大小,外层有个透明背景,中间一部分视为内容区域
// 所以点击内容区域外部视为点击悬浮窗外部
final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的内容区域 view.setOnTouchListener(new OnTouchListener() { @Override
public boolean onTouch(View v, MotionEvent event) { LogUtil.i(LOG_TAG, "onTouch");
int x = (int) event.getX();
int y = (int) event.getY();
Rect rect = new Rect();
popupWindowView.getGlobalVisibleRect(rect);
if (!rect.contains(x, y)) {
WindowUtils.hidePopupWindow();
} LogUtil.i(LOG_TAG, "onTouch : " + x + ", " + y + ", rect: "
+ rect);
return false;
}
});

  点击Back键可隐藏弹窗:

  注意Flag不能设置WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE。

        // 点击back键可消除
view.setOnKeyListener(new OnKeyListener() { @Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
WindowUtils.hidePopupWindow();
return true;
default:
return false;
}
}
});

完整效果

  完整代码:

package com.example.hellowindow;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { private Handler mHandler = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mHandler = new Handler(); Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { mHandler.postDelayed(new Runnable() { @Override
public void run() {
WindowUtils.showPopupWindow(MainActivity.this); }
}, 1000 * 3); }
});
}
}

MainActivity

package com.example.hellowindow;

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button; /**
* 弹窗辅助类
*
* @ClassName WindowUtils
*
*
*/
public class WindowUtils { private static final String LOG_TAG = "WindowUtils";
private static View mView = null;
private static WindowManager mWindowManager = null;
private static Context mContext = null; public static Boolean isShown = false; /**
* 显示弹出框
*
* @param context
* @param view
*/
public static void showPopupWindow(final Context context) {
if (isShown) {
LogUtil.i(LOG_TAG, "return cause already shown");
return;
} isShown = true;
LogUtil.i(LOG_TAG, "showPopupWindow"); // 获取应用的Context
mContext = context.getApplicationContext();
// 获取WindowManager
mWindowManager = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE); mView = setUpView(context); final WindowManager.LayoutParams params = new WindowManager.LayoutParams(); // 类型
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT // 设置flag int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
// | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
// 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,弹出的View收不到Back键的事件
params.flags = flags;
// 不设置这个弹出框的透明遮罩显示为黑色
params.format = PixelFormat.TRANSLUCENT;
// FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
// 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时,后面的应用图标由不可长按变为可长按
// 不设置这个flag的话,home页的划屏会有问题 params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT; params.gravity = Gravity.CENTER; mWindowManager.addView(mView, params); LogUtil.i(LOG_TAG, "add view"); } /**
* 隐藏弹出框
*/
public static void hidePopupWindow() {
LogUtil.i(LOG_TAG, "hide " + isShown + ", " + mView);
if (isShown && null != mView) {
LogUtil.i(LOG_TAG, "hidePopupWindow");
mWindowManager.removeView(mView);
isShown = false;
} } private static View setUpView(final Context context) { LogUtil.i(LOG_TAG, "setUp view"); View view = LayoutInflater.from(context).inflate(R.layout.popupwindow,
null);
Button positiveBtn = (Button) view.findViewById(R.id.positiveBtn);
positiveBtn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { LogUtil.i(LOG_TAG, "ok on click");
// 打开安装包
// 隐藏弹窗
WindowUtils.hidePopupWindow(); }
}); Button negativeBtn = (Button) view.findViewById(R.id.negativeBtn);
negativeBtn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
LogUtil.i(LOG_TAG, "cancel on click");
WindowUtils.hidePopupWindow(); }
}); // 点击窗口外部区域可消除
// 这点的实现主要将悬浮窗设置为全屏大小,外层有个透明背景,中间一部分视为内容区域
// 所以点击内容区域外部视为点击悬浮窗外部
final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的内容区域 view.setOnTouchListener(new OnTouchListener() { @Override
public boolean onTouch(View v, MotionEvent event) { LogUtil.i(LOG_TAG, "onTouch");
int x = (int) event.getX();
int y = (int) event.getY();
Rect rect = new Rect();
popupWindowView.getGlobalVisibleRect(rect);
if (!rect.contains(x, y)) {
WindowUtils.hidePopupWindow();
} LogUtil.i(LOG_TAG, "onTouch : " + x + ", " + y + ", rect: "
+ rect);
return false;
}
}); // 点击back键可消除
view.setOnKeyListener(new OnKeyListener() { @Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
WindowUtils.hidePopupWindow();
return true;
default:
return false;
}
}
}); return view; }
}

WindowUtils

参考资料

  WindowManager:

  http://developer.android.com/reference/android/view/WindowManager.html

  参考实例:

  http://blog.csdn.net/deng0zhaotai/article/details/16827719

  http://www.xsmile.net/?p=538

  http://blog.csdn.net/guolin_blog/article/details/8689140

  简单说明:

  Android之Window、WindowManager与窗口管理:

  http://blog.csdn.net/xieqibao/article/details/6567814

  Android系统服务-WindowManager:

  http://blog.csdn.net/chenyafei617/article/details/6577940

  进一步的学习:

  老罗的Android之旅:

  Android Activity的窗口对象Window的创建过程分析:

  http://blog.csdn.net/luoshengyang/article/details/8223770

  窗口管理服务WindowManagerService的简要介绍和学习计划:

  http://blog.csdn.net/luoshengyang/article/details/8462738

  Android核心分析之窗口管理:

  http://blog.csdn.net/maxleng/article/details/5557758

Android悬浮窗实现 使用WindowManager的更多相关文章

  1. Android 悬浮窗 WindowManager WindowManager.LayoutParamas

    前方高清大图~~~~ 绘制的图片资源: // draw bitmap BitmapDrawable bmpDraw = (BitmapDrawable) getResources().getDrawa ...

  2. Android悬浮窗及其拖动事件

    主页面布局很简单,只有一个RelativelyLayout <?xml version="1.0" encoding="utf-8"?> <R ...

  3. Android 悬浮窗权限校验

    原文:Android 悬浮窗权限校验 悬浮窗权限: <uses-permission android:name="android.permission.SYSTEM_ALERT_WIN ...

  4. Android 悬浮窗、悬浮球开发

    原文:Android 悬浮窗.悬浮球开发 1.权限管理 直接看我另外一篇博客吧,传送门: https://my.oschina.net/u/1462828/blog/1933162 2.Base类Ba ...

  5. Android 悬浮窗 System Alert Window

    悬浮窗能显示在其他应用上方.桌面系统例如Windows,macOS,Ubuntu,打开的程序能以窗口形式显示在屏幕上. 受限于屏幕大小,安卓系统中主要使用多任务切换的方式和分屏的方式.视频播放,视频对 ...

  6. Android 使用WindowManager实现Android悬浮窗

    WindowManager介绍 通过Context.getSystemService(Context.WINDOW_SERVICE)可以获得 WindowManager对象. 每一个WindowMan ...

  7. Android 悬浮窗权限各机型各系统适配大全

    这篇博客主要介绍的是 Android 主流各种机型和各种版本的悬浮窗权限适配,但是由于碎片化的问题,所以在适配方面也无法做到完全的主流机型适配,这个需要大家的一起努力,这个博客的名字永远都是一个将来时 ...

  8. Android 悬浮窗

    悬浮窗是一种比较常见的需求.例如把视频通话界面缩小成一个悬浮窗,然后用户可以在其他界面上处理事情. 本文给出一个简单的悬浮窗实现.可缩小activity和还原大小.可悬浮在其他activity上.使用 ...

  9. 关于Android悬浮窗要获取按键响应的问题

    要在Android中实现顶层的窗口弹出,一般都会用WindowsManager来实现,但是几乎所有的网站资源都是说弹出的悬浮窗不用接受任何按键响应. 而问题就是,我们有时候需要他响应按键,比如电视上的 ...

随机推荐

  1. C#中string.format的格式和用法

    String.Format 方法的几种定义: String.Format (String, Object) 将指定的 String 中的格式项替换为指定的 Object 实例的值的文本等效项. Str ...

  2. Android SDK Manager无法更新的解决

    只需要配置一下hosts文件,在文件的末尾添加下面一句: 74.125.237.1 dl-ssl.google.com windows系统中hosts文件的位置为:C:\Windows\System3 ...

  3. oracle表数据类型number对应java中BIgDecimal转int

    oracle中id为number类型,在java获取id时用getBigDecimal 相匹配, 如果想转换成int,重写model中的getInt方法: public Integer getInt( ...

  4. nodejs学习笔记二——链接mongodb

    a.安装mongoose库用来链接mongodb数据库 安装mongodb数据库参考mongodb安装 前言(怨言) 本来是想安装mongodb库来链接mongodb的,命令行到nodejs工程目录: ...

  5. Visual Studio Code编写HTML

    第一步双击打开Visual Studio Code,我们发现什么也没有,但是有一个默认打开的编辑页面.我们先点击File->OpenFoldor 为什么先这么做呢,有两个原因,第一个原因假如你有 ...

  6. DataTable转换为List<T>或者DataRow转换为T

    这段时间开发ASP.NETMVC应用程序,从数据库获取数据之后,需要把记录转换为数据集在视图中显示.我们需要把DataTable转换为List<T>或者DataRow转换为T. 本篇中可以 ...

  7. exception throw in progress runner thread_VS2015中SVN源代码无说明提交异常

    1-问题描述:通过SVN将代码变更提交服务器时,你可能会遇到以下异常:  exception throw in progress runner thread 2-解决办法: SVN代码源代码管理和TF ...

  8. C# WebClient 使用http免费代理。

    static void Main(string[] args) { WebClient client = new WebClient(); client.Encoding = Encoding.Get ...

  9. XMPP客户端开发(1)--连接和登录

    Smack可用于XMPP客户端的开发,下载Smack,将相关jar文件导入后,即可以开始XMPP客户端的开发. 以下代码实现了客户端连接Tigase服务器,并根据用户名和密码登录. package X ...

  10. 通过“回文字算法”复习C++语言。

    一.什么是回文字 给定一个字符串,从前往后读和从后往前读,字符串序列不变.例如,河北省农村信用社的客服电话是“96369”,无论从后往前读,还是从前后往后读,各个字符出现的位置不变. 二.功能实现 ( ...