package com.xscm.moduleutil.http; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.content.pm.ServiceInfo; import android.os.Build; import android.os.IBinder; import android.view.Gravity; import android.view.View; import androidx.annotation.Nullable; import com.lzf.easyfloat.EasyFloat; import com.lzf.easyfloat.enums.ShowPattern; import com.lzf.easyfloat.enums.SidePattern; import com.xscm.moduleutil.R; public class FloatingWindowService extends Service { private static final int NOTIFICATION_ID = 1; private View floatView; @SuppressLint("WrongConstant") @Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { // Android 14(API 34)及以上需要指定具体的 foregroundServiceType startForeground(NOTIFICATION_ID, buildNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // Android 10 - 13 使用通用类型 startForeground(NOTIFICATION_ID, buildNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST); } else { startForeground(NOTIFICATION_ID, buildNotification()); } // 初始化浮窗(建议使用 ApplicationContext) if (floatView == null) { EasyFloat.with(getApplicationContext()) .setLayout(R.layout.floating_layout) .setTag("testFloat") .setShowPattern(ShowPattern.ALL_TIME) .setDragEnable(true) .setSidePattern(SidePattern.RESULT_HORIZONTAL) .setGravity(Gravity.END) .show(); } // 创建通知防止服务被杀死 // Notification notification = new Notification.Builder(this, "channel_id") // .setContentTitle("浮窗运行中") // .setSmallIcon(R.mipmap.ic_launcher) // .build(); // startForeground(NOTIFICATION_ID, notification); } private Notification buildNotification() { String channelId = "floating_window_service"; String channelName = "悬浮窗服务"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( channelId, channelName, NotificationManager.IMPORTANCE_LOW ); channel.setShowBadge(false); // 不显示角标 channel.setSound(null, null); // 禁止声音 channel.enableVibration(false); // 禁止震动 NotificationManager manager = getSystemService(NotificationManager.class); if (manager != null) { manager.createNotificationChannel(channel); } } Notification.Builder builder = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { builder = new Notification.Builder(this, channelId) .setContentTitle("悬浮窗运行中") .setContentText("点击打开应用") .setSmallIcon(R.mipmap.default_avatar) // ✅ 必须有效存在 .setAutoCancel(true) .setOngoing(true); } return builder.build(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); // 停止浮窗 EasyFloat.dismiss("testFloat"); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }