package com.hdl.photovoltaic.uni;
|
|
import android.app.Notification;
|
import android.app.NotificationChannel;
|
import android.app.NotificationManager;
|
import android.app.Service;
|
import android.content.Intent;
|
import android.os.Build;
|
import android.os.IBinder;
|
|
import androidx.annotation.Nullable;
|
import androidx.core.app.NotificationCompat;
|
|
import com.hdl.photovoltaic.R;
|
|
|
|
public class MyForegroundService extends Service {
|
private static final String CHANNEL_ID = "MyForegroundServiceChannel";
|
private static final int NOTIFICATION_ID = 1;
|
|
private static boolean isRunning = false;
|
|
@Override
|
public void onCreate() {
|
super.onCreate();
|
// 创建通知渠道(Android 8.0+)
|
createNotificationChannel();
|
isRunning = true;
|
|
}
|
// @Override
|
// public void onTaskRemoved(Intent rootIntent) {
|
// super.onTaskRemoved(rootIntent);
|
// isRunning = false;
|
|
/// / // 停止前台状态,移除通知
|
/// / stopForeground(true); // true表示移除通知
|
/// /// // 停止服务
|
/// /// stopSelf();
|
// // 1. 先移除前台状态(可选,但建议)
|
// stopForeground(true);
|
//
|
// // 2. 停止服务
|
// stopSelf();
|
// }
|
@Override
|
public int onStartCommand(Intent intent, int flags, int startId) {
|
// 创建通知
|
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
|
.setContentTitle("")//宿主进程服务
|
.setContentText("")//正在与uni-app保持通信
|
.setSmallIcon(R.drawable.notification_logo) // 必须设置一个图标
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
// .setOngoing(true) // 设置通知为持续通知,不可清除
|
// .setAutoCancel(false) // ← 设置为不可自动取消
|
// .setShowWhen(false) // 不显示时间
|
// .setOnlyAlertOnce(true) // 只提示一次
|
.build();
|
|
// 启动前台服务
|
startForeground(NOTIFICATION_ID, notification);
|
|
// 如果服务被杀死,不再重新创建(重建:START_STICKY,不重建:START_NOT_STICKY)
|
return START_NOT_STICKY;
|
}
|
|
private void createNotificationChannel() {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
NotificationChannel serviceChannel = new NotificationChannel(
|
CHANNEL_ID,
|
getString(R.string.host_process_service_channel),
|
NotificationManager.IMPORTANCE_LOW // 设置为低重要性,不会发出声音
|
);
|
// serviceChannel.setDescription("用于保持宿主进程运行");
|
NotificationManager manager = getSystemService(NotificationManager.class);
|
manager.createNotificationChannel(serviceChannel);
|
}
|
}
|
|
@Nullable
|
@Override
|
public IBinder onBind(Intent intent) {
|
return null;
|
}
|
|
@Override
|
public void onDestroy() {
|
super.onDestroy();
|
isRunning = false;
|
}
|
|
public static boolean isServiceRunning() {
|
return isRunning;
|
}
|
}
|