package com.example.myapplication.Tool;

import static android.content.Context.ACTIVITY_SERVICE;

import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.myapplication.Service.PhotoMonitoringService;

// 更健壮的广播接收器实现示例
public class NotificationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null) return;

        try {
            if ("ACTION_STOP_SERVICE".equals(intent.getAction())) {
                // 防止重复操作
                if (isServiceRunning(context)) {
                    context.stopService(new Intent(context, PhotoMonitoringService.class));
                }

                // 清除所有相关通知
                NotificationManager manager = context.getSystemService(NotificationManager.class);
                manager.cancelAll(); // 或指定ID

                // 可选：发送结果广播
                Intent doneIntent = new Intent("ACTION_SERVICE_STOPPED");
                context.sendBroadcast(doneIntent);
            }
        } catch (Exception e) {
            Log.e("NotificationReceiver", "Error handling action", e);
        }
    }

    private boolean isServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service :
                manager.getRunningServices(Integer.MAX_VALUE)) {
            if (PhotoMonitoringService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}