Android中悬浮窗口的实现原理实例分析
2019/7/7 20:08:26
本文主要是介绍Android中悬浮窗口的实现原理实例分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本文实例讲述了Android中悬浮窗口的实现原理。分享给大家供大家参考。具体如下:
用了我一个周末的时间,个中愤懑就不说了,就这个问题,我翻遍全球网络没有一篇像样的资料,现在将实现原理简单叙述如下:
调用WindowManager,并设置WindowManager.LayoutParams的相关属性,通过WindowManager的addView方法创建View,这样产生出来的View根据WindowManager.LayoutParams属性不同,效果也就不同了。比如创建系统顶级窗口,实现悬浮窗口效果!
WindowManager的方法很简单,基本用到的就三个addView,removeView,updateViewLayout。
而WindowManager.LayoutParams的属性就多了,非常丰富,具体请查看SDK文档。这里给出Android中的WindowManager.java源码,可以具体看一下。
下面是简单示例代码:
public class myFloatView extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button bb=new Button(getApplicationContext()); WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window"); WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams(); /** *以下都是WindowManager.LayoutParams的相关属性 * 具体用途请参考SDK文档 */ wmParams.type=2002; //这里是关键,你也可以试试2003 wmParams.format=1; /** *这里的flags也很关键 *代码实际是wmParams.flags |= FLAG_NOT_FOCUSABLE; *40的由来是wmParams的默认属性(32)+ FLAG_NOT_FOCUSABLE(8) */ wmParams.flags=40; wmParams.width=40; wmParams.height=40; wm.addView(bb, wmParams);//创建View } }
别忘了在AndroidManifest.xml中添加权限:
PS:这里举例说明一下type的值的意思:
/** * Window type: phone. These are non-application windows providing * user interaction with the phone (in particular incoming calls). * These windows are normally placed above all applications, but behind * the status bar. */ public static final int TYPE_PHONE = FIRST_SYSTEM_WINDOW+2; /** * Window type: system window, such as low power alert. These windows * are always on top of application windows. */ public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3;
这个FIRST_SYSTEM_WINDOW的值就是2000。2003和2002的区别就在于2003类型的View比2002类型的还要top,能显示在系统下拉状态栏之上!
希望本文所述对大家的Android程序设计有所帮助。
这篇关于Android中悬浮窗口的实现原理实例分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-01-18android.permission.read_media_video
- 2024-01-18android_getaddrinfo failed eai_nodata
- 2024-01-18androidmo
- 2024-01-15Android下三种离屏渲染技术
- 2024-01-09Android 蓝牙使用
- 2024-01-06Android对接华为AI - 文本识别
- 2023-11-15代码安全之代码混淆及加固(Android)
- 2023-11-10简述Android语音播报TTS
- 2023-11-06Android WiFi工具类
- 2023-07-22Android开发未来的出路