优化前台服务实现

lowmem
Matthew 2 months ago
parent 5151f9291a
commit 7ef6086f50

@ -1,9 +1,14 @@
package com.xypower.mpmaster; package com.xypower.mpmaster;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service; import android.app.Service;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Rect; import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder; import android.os.IBinder;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
@ -16,8 +21,13 @@ import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import androidx.core.app.NotificationCompat;
public class FloatingWindow extends Service { public class FloatingWindow extends Service {
private static final int NOTIFICATION_ID_FOREGROUND_SERVICE = 8466505;
private static final String FOREGROUND_CHANNEL_ID = "floatingwin_mpmst";
private Context mContext; private Context mContext;
private WindowManager mWindowManager; private WindowManager mWindowManager;
private View mView; private View mView;
@ -40,6 +50,28 @@ public class FloatingWindow extends Service {
allAboutLayout(intent); allAboutLayout(intent);
moveView(); 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); return super.onStartCommand(intent, flags, startId);
} }
@ -58,6 +90,21 @@ public class FloatingWindow extends Service {
super.onDestroy(); 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; WindowManager.LayoutParams mWindowsParams;
private void moveView() { private void moveView() {
/* /*

Loading…
Cancel
Save