写一个android 系统级别窗口管理类
时间: 2023-08-16 22:09:10 浏览: 46
以下是一个简单的 Android 系统级别窗口管理类的示例,可以用于显示悬浮窗或通知等:
```java
public class WindowManagerHelper {
private static final String TAG = WindowManagerHelper.class.getSimpleName();
private static WindowManager mWindowManager;
private static WindowManager.LayoutParams mLayoutParams;
/**
* 显示悬浮窗
*
* @param context 上下文
* @param view 悬浮窗视图
*/
public static void showFloatWindow(Context context, View view) {
if (mWindowManager == null) {
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
if (mLayoutParams == null) {
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mLayoutParams.format = PixelFormat.RGBA_8888;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.gravity = Gravity.CENTER;
mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
try {
mWindowManager.addView(view, mLayoutParams);
} catch (Exception e) {
Log.e(TAG, "showFloatWindow: " + e.getMessage());
}
}
/**
* 隐藏悬浮窗
*
* @param context 上下文
* @param view 悬浮窗视图
*/
public static void hideFloatWindow(Context context, View view) {
if (mWindowManager != null) {
try {
mWindowManager.removeView(view);
} catch (Exception e) {
Log.e(TAG, "hideFloatWindow: " + e.getMessage());
}
}
}
/**
* 显示通知
*
* @param context 上下文
* @param title 通知标题
* @param content 通知内容
*/
public static void showNotification(Context context, String title, String content) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true);
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
/**
* 取消通知
*
* @param context 上下文
*/
public static void cancelNotification(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
}
```
这个类中包含了显示悬浮窗和通知的方法,可以根据实际需求进行修改和扩展。注意,在 Android 8.0 以上的版本中,需要使用 TYPE_APPLICATION_OVERLAY 类型的窗口才能显示悬浮窗。