diff --git a/app/src/main/java/com/xypower/mpapp/FloatingWindow.java b/app/src/main/java/com/xypower/mpapp/FloatingWindow.java index 3ce4025c..963e861f 100644 --- a/app/src/main/java/com/xypower/mpapp/FloatingWindow.java +++ b/app/src/main/java/com/xypower/mpapp/FloatingWindow.java @@ -1,9 +1,14 @@ package com.xypower.mpapp; +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Rect; +import android.os.Build; +import android.os.Handler; import android.os.IBinder; import android.text.Editable; import android.text.TextWatcher; @@ -16,8 +21,13 @@ import android.widget.Button; import android.widget.EditText; import android.widget.TextView; +import androidx.core.app.NotificationCompat; + public class FloatingWindow extends Service { + private static final int NOTIFICATION_ID_FOREGROUND_SERVICE = 8466506; + private static final String FOREGROUND_CHANNEL_ID = "floatingwin_mpapp"; + private Context mContext; private WindowManager mWindowManager; private View mView; @@ -40,6 +50,29 @@ public class FloatingWindow extends Service { allAboutLayout(intent); moveView(); + final Context context = getApplicationContext(); + Handler handler = new Handler(); + handler.postDelayed(new Runnable() { + @Override + public void run() { + try { + createNotificationChannel(); + + Notification notification = new NotificationCompat.Builder(context, FOREGROUND_CHANNEL_ID) + .setContentTitle("FloatingWindow") + .setContentText("App Running") + // .setSmallIcon(R.drawable.ic_notification) + .setPriority(NotificationCompat.PRIORITY_LOW) + .build(); + + // 启动前台服务 + startForeground(NOTIFICATION_ID_FOREGROUND_SERVICE, notification); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + }, 4000); + return super.onStartCommand(intent, flags, startId); } @@ -58,6 +91,21 @@ public class FloatingWindow extends Service { super.onDestroy(); } + private void createNotificationChannel() { + // >= Android 8.0 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationChannel channel = new NotificationChannel( + FOREGROUND_CHANNEL_ID, + "FloatingWindow", + NotificationManager.IMPORTANCE_LOW); + + NotificationManager manager = getSystemService(NotificationManager.class); + if (manager != null) { + manager.createNotificationChannel(channel); + } + } + } + WindowManager.LayoutParams mWindowsParams; private void moveView() { /*