要实现Android悬浮窗,可以按照以下步骤进行编写代码:
- 在AndroidManifest.xml文件中添加悬浮窗权限:
- 创建一个Service类来实现悬浮窗功能,例如FloatWindowService:
public class FloatWindowService extends Service { private WindowManager mWindowManager; private View mFloatView; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); mFloatView = LayoutInflater.from(this).inflate(R.layout.layout_float_window, null); WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT ); params.gravity = Gravity.LEFT | Gravity.TOP; params.x = 0; params.y = 0; mWindowManager.addView(mFloatView, params); } @Override public void onDestroy() { super.onDestroy(); if (mWindowManager != null && mFloatView != null) { mWindowManager.removeView(mFloatView); } } }
- 在res/layout文件夹下创建一个布局文件layout_float_window.xml,用于定义悬浮窗的布局,例如:
- 在MainActivity中启动FloatWindowService:
Intent intent = new Intent(this, FloatWindowService.class); startService(intent);
这样就可以实现一个简单的Android悬浮窗功能了。当然,实际应用中可能还需要添加一些其他功能,比如拖动悬浮窗、点击事件处理等。