Android悬浮窗的实现
下面来讲解一下悬浮窗的具体实现方式。
完整的源码地址:https://github.com/dongzhong/TestForFloatingWindow
为了让悬浮窗与Activity脱离,使其在应用处于后台时悬浮窗仍然可以正常运行,这里使用Service来启动悬浮窗并做为其背后逻辑支撑。
在启动服务之前,需要先判断一下当前是否允许开启悬浮窗。
(MainActivity.java)
public void startFloatingService(View view) { ... if (!Settings.canDrawOverlays(this)) { Toast.makeText(this, "当前无权限,请授权", Toast.LENGTH_SHORT); startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0); } else { startService(new Intent(MainActivity.this, FloatingService.class)); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0) { if (!Settings.canDrawOverlays(this)) { Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show(); startService(new Intent(MainActivity.this, FloatingService.class)); } } }
悬浮窗控件可以是任意的View
的子类类型。这里先以一个最简单的Button
来做示例。
(FloatingService.java)
@Override public int onStartCommand(Intent intent, int flags, int startId) { showFloatingWindow(); return super.onStartCommand(intent, flags, startId); } private void showFloatingWindow() { if (Settings.canDrawOverlays(this)) { // 获取WindowManager服务 WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); // 新建悬浮窗控件 Button button = new Button(getApplicationContext()); button.setText("Floating Window"); button.setBackgroundColor(Color.BLUE); // 设置LayoutParam WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; } layoutParams.format = PixelFormat.RGBA_8888; layoutParams.width = 500; layoutParams.height = 100; layoutParams.x = 300; layoutParams.y = 300; // 将悬浮窗控件添加到WindowManager windowManager.addView(button, layoutParams); } }
好了,完成了!
对,没看错,最简单的悬浮窗这就实现了。是不是很简单?来看看效果吧
当然了,这个悬浮窗的效果仅仅是显示出来,离真正想要的效果还相差甚远。不过基础的原理是已经实现了,剩下的就是要在这上面一点点的添加功能啦。
若文章对您有帮助,帮忙点个赞!
(微信扫码即可登录,无需注册)