在Android的非活动类中打开一个小窗口可以通过使用系统提供的WindowManager类来实现。下面是一个实现的步骤:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
public class FloatingWindowService extends Service {
private WindowManager mWindowManager;
private View mFloatingView;
@Override
public void onCreate() {
super.onCreate();
// 初始化WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
// 创建并设置小窗口的布局
mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_window_layout, null);
// 设置小窗口的参数
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
// 添加小窗口到WindowManager
mWindowManager.addView(mFloatingView, params);
}
@Override
public void onDestroy() {
super.onDestroy();
// 移除小窗口
if (mFloatingView != null) {
mWindowManager.removeView(mFloatingView);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Intent intent = new Intent(context, FloatingWindowService.class);
context.startService(intent);
需要注意的是,从Android 10(API级别29)开始,需要使用WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY作为小窗口的类型,以确保小窗口可以显示在其他应用之上。
领取专属 10元无门槛券
手把手带您无忧上云