android 实现悬浮窗功能
时间: 2023-12-07 08:02:47 浏览: 201
Android 实现悬浮窗功能
1. 在 AndroidManifest.xml 文件中添加权限:
```xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
```
2. 创建一个服务类,继承自 Service:
```java
public class FloatingService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createFloatingWindow();
return super.onStartCommand(intent, flags, startId);
}
private void createFloatingWindow() {
// 创建悬浮窗
}
@Override
public void onDestroy() {
super.onDestroy();
// 关闭悬浮窗
}
}
```
3. 在 onCreate() 方法中启动服务:
```java
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, FloatingService.class);
startService(intent);
}
```
4. 在 createFloatingWindow() 方法中创建悬浮窗:
```java
private void createFloatingWindow() {
// 初始化 WindowManager
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
// 创建悬浮窗布局
View floatingView = LayoutInflater.from(this).inflate(R.layout.floating_window, null);
// 设置悬浮窗布局参数
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
layoutParams.format = PixelFormat.TRANSLUCENT;
layoutParams.gravity = Gravity.CENTER;
// 添加悬浮窗布局到 WindowManager 中
windowManager.addView(floatingView, layoutParams);
}
```
5. 在 onDestroy() 方法中关闭悬浮窗:
```java
@Override
public void onDestroy() {
super.onDestroy();
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.removeView(floatingView);
}
```
6. 创建悬浮窗布局文件 floating_window.xml:
```xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="悬浮窗"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
```
7. 运行程序即可看到悬浮窗。
阅读全文