导航菜单

页面标题

页面副标题

xDrip+ v04633772025.07.16 - Notifications.java 源代码

正在查看: xDrip+ v04633772025.07.16 应用的 Notifications.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.eveningoutpost.dexdrip.utilitymodels;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.util.Log;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.eveningoutpost.dexdrip.AddCalibration;
import com.eveningoutpost.dexdrip.BestGlucose;
import com.eveningoutpost.dexdrip.DoubleCalibrationActivity;
import com.eveningoutpost.dexdrip.EditAlertActivity;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.driver.UsbId;
import com.eveningoutpost.dexdrip.models.ActiveBgAlert;
import com.eveningoutpost.dexdrip.models.AlertType;
import com.eveningoutpost.dexdrip.models.BgReading;
import com.eveningoutpost.dexdrip.models.Calibration;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.models.Sensor;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.models.UserNotification;
import com.eveningoutpost.dexdrip.services.ActivityRecognizedService;
import com.eveningoutpost.dexdrip.services.MissedReadingService;
import com.eveningoutpost.dexdrip.services.SnoozeOnNotificationDismissService;
import com.eveningoutpost.dexdrip.services.broadcastservice.BroadcastEntry;
import com.eveningoutpost.dexdrip.ui.NumberGraphic;
import com.eveningoutpost.dexdrip.utilitymodels.ColorCache;
import com.eveningoutpost.dexdrip.utils.DexCollectionType;
import com.eveningoutpost.dexdrip.wearintegration.Amazfitservice;
import com.eveningoutpost.dexdrip.xdrip;
import java.util.Date;
import java.util.List;

public class Notifications extends IntentService {
    public static String bg_notification_sound;
    public static boolean bg_notifications;
    public static boolean bg_notifications_watch;
    public static boolean bg_ongoing;
    public static boolean bg_persistent_high_alert_enabled_watch;
    public static boolean bg_sound_in_silent;
    public static String calibration_notification_sound;
    public static boolean calibration_notifications;
    public static boolean calibration_override_silent;
    public static int calibration_snooze;
    public static boolean doMgdl;
    public static boolean smart_alerting;
    public static boolean smart_snoozing;
    private static volatile PendingIntent wakeIntent;
    private BestGlucose.DisplayGlucose dg;
    Bitmap iconBitmap;
    Context mContext;
    Bitmap notifiationBitmap;
    SharedPreferences prefs;
    public static final long[] vibratePattern = {0, 1000, 300, 1000, 300, 1000};
    private static final String TAG = AlertPlayer.class.getSimpleName();
    private static String last_noise_string = "Startup";
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private static boolean low_notifying = false;

    public Notifications() {
        super("Notifications");
        UserError.Log.i("Notifications", "Creating Notifications Intent Service");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        PowerManager.WakeLock wakeLock = JoH.getWakeLock("NotificationsService", UsbId.SILABS_CP2102);
        try {
            UserError.Log.d("Notifications", "Running Notifications Intent Service");
            Context applicationContext = getApplicationContext();
            if (Pref.getBoolean("motion_tracking_enabled", false)) {
                ActivityRecognizedService.reStartActivityRecogniser(applicationContext);
            }
            ReadPerfs(applicationContext);
            scheduleWakeup(applicationContext, notificationSetter(applicationContext));
            applicationContext.startService(new Intent(applicationContext, (Class<?>) MissedReadingService.class));
        } finally {
            JoH.releaseWakeLock(wakeLock);
        }
    }

    public void ReadPerfs(Context context) {
        this.mContext = context;
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        this.prefs = defaultSharedPreferences;
        bg_notifications = defaultSharedPreferences.getBoolean("bg_notifications", true);
        bg_notifications_watch = PersistentStore.getBoolean("bg_notifications_watch");
        bg_persistent_high_alert_enabled_watch = PersistentStore.getBoolean("persistent_high_alert_enabled_watch");
        bg_notification_sound = this.prefs.getString("bg_notification_sound", "content://settings/system/notification_sound");
        bg_sound_in_silent = this.prefs.getBoolean("bg_sound_in_silent", false);
        calibration_notifications = this.prefs.getBoolean("calibration_notifications", false);
        calibration_snooze = Integer.parseInt(this.prefs.getString("calibration_snooze", "20"));
        calibration_override_silent = this.prefs.getBoolean("calibration_alerts_override_silent", false);
        calibration_notification_sound = this.prefs.getString("calibration_notification_sound", "content://settings/system/notification_sound");
        doMgdl = this.prefs.getString("units", "mgdl").compareTo("mgdl") == 0;
        smart_snoozing = this.prefs.getBoolean("smart_snoozing", true);
        smart_alerting = this.prefs.getBoolean("smart_alerting", true);
        bg_ongoing = this.prefs.getBoolean("run_service_in_foreground", false);
    }

    private void FileBasedNotifications(Context context) {
        double d;
        AlertType HigherAlert;
        ReadPerfs(context);
        Sensor currentSensor = Sensor.currentSensor();
        BgReading last = BgReading.last();
        if (last == null) {
            AlertPlayer.getPlayer().stopAlert(context, true, false);
            return;
        }
        BestGlucose.DisplayGlucose displayGlucose = BestGlucose.getDisplayGlucose();
        this.dg = displayGlucose;
        if (displayGlucose != null) {
            d = displayGlucose.mgdl;
            last.calculated_value = d;
        } else {
            d = last.calculated_value;
            UserError.Log.wtf(TAG, "Could not obtain best glucose value!");
        }
        String str = TAG;
        UserError.Log.d(str, "FileBasedNotifications called bgReading.calculated_value = " + last.calculated_value + " calculated value: " + d);
        if ((currentSensor != null || Home.get_follower()) && d != BgReading.BESTOFFSET) {
            AlertType alertType = AlertType.get_highest_active_alert(context, d);
            if (alertType == null) {
                UserError.Log.d(str, "FileBasedNotifications - No active notifcation exists, stopping all alerts");
                AlertPlayer.getPlayer().stopAlert(context, false, true);
                return;
            }
            AlertType alertTypegetOnly = ActiveBgAlert.alertTypegetOnly();
            if (alertTypegetOnly == null) {
                UserError.Log.d(str, "FileBasedNotifications we have a new alert, starting to play it... " + alertType.name);
                AlertPlayer.getPlayer().startAlert(context, trendingToAlertEnd(context, Boolean.TRUE, alertType), alertType, EditAlertActivity.unitsConvert2Disp(doMgdl, d));
                return;
            }
            if (alertTypegetOnly.uuid.equals(alertType.uuid)) {
                if (this.prefs.getBoolean("disable_alerts_stale_data", false)) {
                    if ((new Date().getTime() - ((Integer.parseInt(this.prefs.getString("disable_alerts_stale_data_minutes", "15")) + 2) * UsbId.SILABS_CP2102)) - BgReading.lastNoSenssor().timestamp > 0) {
                        UserError.Log.d(str, "FileBasedNotifications : active alert found but not replaying it because more than three readings missed :  " + alertType.name);
                        return;
                    }
                }
                UserError.Log.d(str, "FileBasedNotifications we have found an active alert, checking if we need to play it " + alertType.name);
                AlertPlayer.getPlayer().ClockTick(context, trendingToAlertEnd(context, Boolean.FALSE, alertType), EditAlertActivity.unitsConvert2Disp(doMgdl, d));
                return;
            }
            if (ActiveBgAlert.alertSnoozeOver()) {
                UserError.Log.d(str, "FileBasedNotifications we had two alerts, the snoozed one is over, we fall down to deleting the snoozed and staring the new");
            } else if (!AlertType.OpositeDirection(alertTypegetOnly, alertType) && (HigherAlert = AlertType.HigherAlert(alertTypegetOnly, alertType)) == alertTypegetOnly) {
                UserError.Log.d(str, "FileBasedNotifications The new alert has the same direcotion, it is lower than the one snoozed, not playing it. newHigherAlert = " + HigherAlert.name + "activeBgAlert = " + alertTypegetOnly.name);
                return;
            }
            UserError.Log.d(str, "Found a new alert, that is higher than the previous one will play it. " + alertType.name);
            AlertPlayer.getPlayer().stopAlert(context, true, false);
            AlertPlayer.getPlayer().startAlert(context, trendingToAlertEnd(context, Boolean.TRUE, alertType), alertType, EditAlertActivity.unitsConvert2Disp(doMgdl, d));
            return;
        }
        AlertPlayer.getPlayer().stopAlert(context, true, false);
    }

    boolean trendingToAlertEnd(Context context, Boolean bool, AlertType alertType) {
        if (bool.booleanValue() && !smart_alerting) {
            return false;
        }
        if (bool.booleanValue() || smart_snoozing) {
            return BgReading.trendingToAlertEnd(context, alertType.above);
        }
        return false;
    }

    private boolean notificationSetter(android.content.Context r14) {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.utilitymodels.Notifications.notificationSetter(android.content.Context):boolean");
    }

    private long calcuatleArmTimeUnclearalert(Context context, long j, boolean z) {
        if (!z) {
            return Long.MAX_VALUE;
        }
        UserNotification GetNotificationByType = UserNotification.GetNotificationByType("bg_unclear_readings_alert");
        if (GetNotificationByType == null) {
            UserError.Log.i(TAG, "No active alert exists. returning Long.MAX_VALUE");
            return Long.MAX_VALUE;
        }
        Long valueOf = Long.valueOf((long) GetNotificationByType.timestamp);
        if (valueOf.longValue() < j) {
            valueOf = Long.valueOf(j);
        }
        if (valueOf.longValue() == Long.MAX_VALUE) {
            UserError.Log.e(TAG, "calcuatleArmTimeUnclearalert wakeTimeUnclear bad value setting it to one minute from now " + new Date(valueOf.longValue()) + " in " + ((valueOf.longValue() - j) / 60000.0d) + " minutes");
            return j + 60000;
        }
        UserError.Log.w(TAG, "calcuatleArmTimeUnclearalert returning " + new Date(valueOf.longValue()) + " in " + ((valueOf.longValue() - j) / 60000.0d) + " minutes");
        return valueOf.longValue();
    }

    private long calcuatleArmTimeBg(long j) {
        Long l = Long.MAX_VALUE;
        ActiveBgAlert only = ActiveBgAlert.getOnly();
        if (only != null && AlertType.get_alert(only.alert_uuid) != null) {
            l = only.next_alert_at;
            String str = TAG;
            UserError.Log.d(str, "ArmTimer BG alert -waking at: " + new Date(l.longValue()) + " in " + ((l.longValue() - j) / 60000.0d) + " minutes");
            if (l.longValue() < j) {
                l = Long.valueOf(60000 + j);
                UserError.Log.w(str, "setting next alert to 1 minute from now (no problem right now, but needs a fix someplace else)");
            }
        }
        UserError.Log.d("Notifications", "calcuatleArmTimeBg returning: " + new Date(l.longValue()) + " in " + ((l.longValue() - j) / 60000.0d) + " minutes");
        return l.longValue();
    }

    private long calcuatleArmTime(Context context, long j, boolean z) {
        Long valueOf = Long.valueOf(Math.min(Long.valueOf(calcuatleArmTimeBg(j)).longValue(), Long.valueOf(calcuatleArmTimeUnclearalert(context, j, z)).longValue()));
        UserError.Log.d("Notifications", "calcuatleArmTime returning: " + new Date(valueOf.longValue()) + " in " + ((valueOf.longValue() - j) / 60000.0d) + " minutes");
        return valueOf.longValue();
    }

    private synchronized void scheduleWakeup(Context context, boolean z) {
        long tsl = JoH.tsl();
        long calcuatleArmTime = calcuatleArmTime(context, tsl, z);
        if (calcuatleArmTime < tsl) {
            UserError.Log.e("Notifications", "ArmTimer recieved a negative time, will fire in 6 minutes");
            calcuatleArmTime = tsl + 360000;
        } else {
            long j = 360000 + tsl;
            if (calcuatleArmTime >= j) {
                UserError.Log.i("Notifications", "ArmTimer recieved a biger time, will fire in 6 minutes");
                calcuatleArmTime = j;
            } else if (calcuatleArmTime == tsl) {
                UserError.Log.e("Notifications", "should arm right now, waiting one more second to avoid infinitue loop");
                calcuatleArmTime = 1000 + tsl;
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append("ArmTimer waking at: ");
        sb.append(new Date(calcuatleArmTime));
        sb.append(" in ");
        long j2 = calcuatleArmTime - tsl;
        sb.append(j2 / 60000.0d);
        sb.append(" minutes");
        UserError.Log.d("Notifications", sb.toString());
        if (wakeIntent == null) {
            wakeIntent = PendingIntent.getService(this, 0, new Intent(this, getClass()), 0);
        }
        JoH.wakeUpIntent(context, j2, wakeIntent);
    }

    private boolean useOngoingChannel() {
        return Pref.getBooleanDefaultFalse("use_notification_channels") && Pref.getBooleanDefaultFalse("ongoing_notification_channel") && Build.VERSION.SDK_INT >= 26;
    }

    public synchronized Notification createOngoingNotification(BgGraphBuilder bgGraphBuilder, Context context) {
        Notification.Builder builder;
        CharSequence charSequence;
        Object unitizedDeltaString;
        String str;
        Bitmap smallIconBitmap;
        this.mContext = context;
        ReadPerfs(context);
        Intent intent = new Intent(this.mContext, (Class<?>) Home.class);
        List<BgReading> latest = BgReading.latest(2);
        Bitmap bitmap = null;
        boolean z = false;
        BgReading bgReading = (latest == null || latest.size() < 2) ? null : latest.get(0);
        TaskStackBuilder create = TaskStackBuilder.create(this.mContext);
        create.addParentStack(Home.class);
        create.addNextIntent(intent);
        PendingIntent pendingIntent = create.getPendingIntent(0, 134217728);
        if (useOngoingChannel() && Build.VERSION.SDK_INT >= 26) {
            builder = new Notification.Builder(this.mContext, "ongoingChannel");
            builder.setSound(null);
        } else {
            builder = new Notification.Builder(this.mContext);
        }
        builder.setOngoing(Pref.getBoolean("use_proper_ongoing", true));
        try {
            builder.setGroup("xDrip ongoing");
        } catch (Exception unused) {
        }
        builder.setVisibility(Pref.getBooleanDefaultFalse("public_notifications") ? 1 : 0);
        builder.setCategory("status");
        if (Pref.getBooleanDefaultFalse("high_priority_notifications")) {
            builder.setPriority(1);
        }
        BestGlucose.DisplayGlucose displayGlucose = BestGlucose.getDisplayGlucose();
        if (bgReading == null) {
            charSequence = "BG Reading Unavailable";
        } else if (displayGlucose != null) {
            charSequence = displayGlucose.spannableString(displayGlucose.unitized + " " + displayGlucose.delta_arrow, false);
        } else {
            charSequence = bgReading.displayValue(this.mContext) + " " + bgReading.slopeArrow();
        }
        SpannableString spannableString = new SpannableString(charSequence);
        builder.setContentTitle(spannableString).setContentText("xDrip Data collection service is running.").setSmallIcon(2131230884).setUsesChronometer(false);
        if (SystemClock.uptimeMillis() > 900000) {
            if (NumberGraphic.numberIconEnabled() && displayGlucose != null && !displayGlucose.isStale() && (smallIconBitmap = NumberGraphic.getSmallIconBitmap(displayGlucose.unitized)) != null) {
                builder.setSmallIcon(Icon.createWithBitmap(smallIconBitmap));
            }
            if (NumberGraphic.largeWithArrowEnabled()) {
                if (displayGlucose != null && !displayGlucose.isStale()) {
                    bitmap = NumberGraphic.getLargeWithArrowBitmap(displayGlucose.unitized, displayGlucose.delta_arrow);
                }
            } else if (NumberGraphic.largeNumberIconEnabled() && displayGlucose != null && !displayGlucose.isStale()) {
                bitmap = NumberGraphic.getLargeIconBitmap(displayGlucose.unitized);
            }
        }
        if (bgReading != null) {
            builder.setWhen(bgReading.timestamp);
            builder.setShowWhen(true);
            StringBuilder sb = new StringBuilder();
            sb.append("Delta: ");
            if (displayGlucose != null) {
                StringBuilder sb2 = new StringBuilder();
                sb2.append(displayGlucose.unitized_delta);
                if (displayGlucose.from_plugin) {
                    str = " " + context.getString(2131755982);
                } else {
                    str = "";
                }
                sb2.append(str);
                unitizedDeltaString = displayGlucose.spannableString(sb2.toString());
            } else {
                unitizedDeltaString = bgGraphBuilder.unitizedDeltaString(true, true);
            }
            sb.append(unitizedDeltaString);
            SpannableString spannableString2 = new SpannableString(sb.toString());
            builder.setContentText(spannableString2);
            BgSparklineBuilder showAxes = new BgSparklineBuilder(this.mContext).setBgGraphBuilder(bgGraphBuilder).showHighLine().showLowLine().setStart(System.currentTimeMillis() - 10800000).showAxes(true);
            ColorCache.X x = ColorCache.X.color_notification_chart_background;
            BgSparklineBuilder backgroundColor = showAxes.setBackgroundColor(ColorCache.getCol(x));
            if (DexCollectionType.hasFiltered() && Pref.getBooleanDefaultFalse("show_filtered_curve")) {
                z = true;
            }
            this.notifiationBitmap = backgroundColor.setShowFiltered(z).build();
            Notification.DecoratedCustomViewStyle decoratedCustomViewStyle = new Notification.DecoratedCustomViewStyle();
            if (bitmap == null) {
                bitmap = new BgSparklineBuilder(this.mContext).setHeight(64.0f).showLowLine().showHighLine().setStart(System.currentTimeMillis() - 10800000).setBgGraphBuilder(bgGraphBuilder).setBackgroundColor(ColorCache.getCol(x)).build();
            }
            this.iconBitmap = bitmap;
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), 2131493032);
            remoteViews.setImageViewBitmap(2131296818, this.iconBitmap);
            remoteViews.setTextViewText(2131296822, spannableString);
            remoteViews.setTextViewText(2131296821, spannableString2);
            RemoteViews remoteViews2 = new RemoteViews(context.getPackageName(), 2131493033);
            remoteViews2.setImageViewBitmap(2131296818, this.notifiationBitmap);
            remoteViews2.setTextViewText(2131296822, spannableString);
            remoteViews2.setTextViewText(2131296821, spannableString2);
            builder.setStyle(decoratedCustomViewStyle).setCustomContentView(remoteViews).setCustomBigContentView(remoteViews2);
        }
        builder.setContentIntent(pendingIntent);
        builder.setLocalOnly(true);
        builder.setOnlyAlertOnce(true);
        return XdripNotification.build(builder);
    }

    private synchronized void bgOngoingNotification(final BgGraphBuilder bgGraphBuilder) {
        try {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        NotificationManagerCompat from = NotificationManagerCompat.from(Notifications.this.mContext);
                        Notifications notifications = Notifications.this;
                        from.notify(8811, notifications.createOngoingNotification(bgGraphBuilder, notifications.mContext));
                        Bitmap bitmap = Notifications.this.iconBitmap;
                        if (bitmap != null) {
                            bitmap.recycle();
                        }
                        Bitmap bitmap2 = Notifications.this.notifiationBitmap;
                        if (bitmap2 != null) {
                            bitmap2.recycle();
                        }
                    } catch (RuntimeException e) {
                        UserError.Log.e(Notifications.TAG, "Got runtime exception in bgOngoingNotification runnable: ", e);
                        Home.toaststaticnext("Problem displaying ongoing notification");
                    }
                }
            });
        } catch (RuntimeException e) {
            UserError.Log.e(TAG, "Got runtime exception in bgOngoingNotification: ", e);
            Home.toaststaticnext("Problem displaying ongoing notification");
        }
    }

    private void reportNoiseChanges() {
        String noiseString = BgGraphBuilder.noiseString(BgGraphBuilder.last_noise);
        if (BgGraphBuilder.noiseString(BgGraphBuilder.last_noise).equals(last_noise_string)) {
            return;
        }
        UserError.Log.uel("Noise", "Changed from: " + last_noise_string + " to " + noiseString);
        last_noise_string = noiseString;
    }

    private void evaluateLowPredictionAlarm() {
        if (this.prefs.getBoolean("predict_lows_alarm", false)) {
            double currentLowOccursAt = BgGraphBuilder.getCurrentLowOccursAt();
            if (currentLowOccursAt > BgReading.BESTOFFSET && BgGraphBuilder.last_noise < 60.0d) {
                double d = JoH.tolerantParseDouble(this.prefs.getString("low_predict_alarm_level", "40"), 40.0d);
                double ts = (currentLowOccursAt - JoH.ts()) / 60000.0d;
                Log.d(TAG, "evaluateLowPredictionAlarm: mins: " + ts);
                if (ts <= 1.0d) {
                    if (low_notifying) {
                        lowPredictAlert(xdrip.getAppContext(), false, "");
                        low_notifying = false;
                        return;
                    }
                    return;
                }
                if (ts < d) {
                    lowPredictAlert(xdrip.getAppContext(), true, getString(2131755790) + " " + getString(2131755681) + " " + ((int) ts) + getString(2131756395));
                    low_notifying = true;
                    return;
                }
                lowPredictAlert(xdrip.getAppContext(), false, "");
                return;
            }
            if (low_notifying) {
                lowPredictAlert(xdrip.getAppContext(), false, "");
                low_notifying = false;
            }
        }
    }

    private void clearAllCalibrationNotifications() {
        notificationDismiss(2);
        notificationDismiss(4);
        notificationDismiss(3);
    }

    private void calibrationNotificationCreate(String str, String str2, Intent intent, int i) {
        NotificationCompat.Builder notificationBuilder = notificationBuilder(str, str2, intent, "calibrationChannel");
        notificationBuilder.setVisibility(Pref.getBooleanDefaultFalse("public_notifications") ? 1 : 0);
        notificationBuilder.setVibrate(vibratePattern);
        notificationBuilder.setLights(-16711936, 300, 1000);
        if (calibration_override_silent) {
            notificationBuilder.setSound(Uri.parse(calibration_notification_sound), 4);
        } else {
            notificationBuilder.setSound(Uri.parse(calibration_notification_sound));
        }
        ((NotificationManager) this.mContext.getSystemService("notification")).notify(i, XdripNotificationCompat.build(notificationBuilder));
    }

    private NotificationCompat.Builder notificationBuilder(String str, String str2, Intent intent, String str3) {
        return new NotificationCompat.Builder(this.mContext, str3).setVisibility(Pref.getBooleanDefaultFalse("public_notifications") ? 1 : 0).setSmallIcon(2131230884).setContentTitle(str).setContentText(str2).setPriority(Pref.getBooleanDefaultFalse("high_priority_notifications") ? 2 : 1).setContentIntent(notificationIntent(intent));
    }

    private PendingIntent notificationIntent(Intent intent) {
        return PendingIntent.getActivity(this.mContext, 0, intent, 134217728);
    }

    private void notificationDismiss(int i) {
        ((NotificationManager) this.mContext.getSystemService("notification")).cancel(i);
    }

    private void calibrationRequest() {
        UserNotification lastCalibrationAlert = UserNotification.lastCalibrationAlert();
        if (lastCalibrationAlert == null || lastCalibrationAlert.timestamp <= new Date().getTime() - (calibration_snooze * UsbId.SILABS_CP2102)) {
            if (lastCalibrationAlert != null) {
                lastCalibrationAlert.delete();
            }
            long msSinceLastCalibration = Calibration.msSinceLastCalibration() / 3600000;
            UserNotification.create(msSinceLastCalibration + " hours since last Calibration  (@" + JoH.hourMinuteString() + ")", "calibration_alert", new Date().getTime());
            StringBuilder sb = new StringBuilder();
            sb.append(msSinceLastCalibration);
            sb.append(" hours since last calibration");
            calibrationNotificationCreate("Calibration Needed", sb.toString(), new Intent(this.mContext, (Class<?>) AddCalibration.class), 2);
        }
    }

    private void doubleCalibrationRequest() {
        UserNotification lastDoubleCalibrationAlert = UserNotification.lastDoubleCalibrationAlert();
        if (lastDoubleCalibrationAlert == null || lastDoubleCalibrationAlert.timestamp <= new Date().getTime() - (calibration_snooze * UsbId.SILABS_CP2102)) {
            if (lastDoubleCalibrationAlert != null) {
                lastDoubleCalibrationAlert.delete();
            }
            UserNotification.create("Double Calibration", "double_calibration_alert", new Date().getTime());
            calibrationNotificationCreate("Sensor is ready", getString(2131756287) + "  (@" + JoH.hourMinuteString() + ")", new Intent(this.mContext, (Class<?>) DoubleCalibrationActivity.class), 2);
        }
    }

    private void extraCalibrationRequest() {
        UserNotification lastExtraCalibrationAlert = UserNotification.lastExtraCalibrationAlert();
        if (lastExtraCalibrationAlert == null || lastExtraCalibrationAlert.timestamp <= new Date().getTime() - (calibration_snooze * UsbId.SILABS_CP2102)) {
            if (lastExtraCalibrationAlert != null) {
                lastExtraCalibrationAlert.delete();
            }
            UserNotification.create("Extra Calibration Requested", "extra_calibration_alert", new Date().getTime());
            calibrationNotificationCreate("Calibration Requested", "Increase performance by calibrating now  (@" + JoH.hourMinuteString() + ")", new Intent(this.mContext, (Class<?>) AddCalibration.class), 4);
        }
    }

    public static void bgUnclearAlert(Context context) {
        OtherAlert(context, "bg_unclear_readings_alert", "Unclear Sensor Readings  (@" + JoH.hourMinuteString() + ")", 7, "bgAlertChannel", true, MissedReadingService.getOtherAlertReraiseSec(context, "bg_unclear_readings_alert"));
    }

    public static void bgMissedAlert(Context context) {
        OtherAlert(context, "bg_missed_alerts", context.getString(2131755215) + "  (@" + JoH.hourMinuteString() + ")", 8, "bgMissedAlertChannel", true, MissedReadingService.getOtherAlertReraiseSec(context, "bg_missed_alerts"));
    }

    public static void ob1SessionRestartRequested() {
        Context appContext = xdrip.getAppContext();
        OtherAlert(appContext, "ob1_session_restart", appContext.getString(2131755951), appContext.getString(2131755949), 14, "calibrationChannel", true, 0L);
    }

    public static void RisingAlert(Context context, boolean z) {
        RiseDropAlert(context, z, "bg_rise_alert", context.getString(2131755217) + "  (@" + JoH.hourMinuteString() + ")", 9);
    }

    public static void DropAlert(Context context, boolean z) {
        RiseDropAlert(context, z, "bg_fall_alert", context.getString(2131755214) + "  (@" + JoH.hourMinuteString() + ")", 10);
    }

    public static void lowPredictAlert(Context context, boolean z, String str) {
        if (!z) {
            ((NotificationManager) context.getSystemService("notification")).cancel(11);
            UserNotification.DeleteNotificationByType("bg_predict_alert");
            return;
        }
        if (Pref.getLong("alerts_disabled_until", 0L) < JoH.tsl() && Pref.getLong("low_alerts_disabled_until", 0L) < JoH.tsl()) {
            OtherAlert(context, "bg_predict_alert", str, 11, "bgPredictedLowChannel", false, 1200L);
            if (Pref.getBooleanDefaultFalse("speak_alerts") && JoH.pratelimit("low-predict-speak", 1800)) {
                SpeechUtil.say(str, 4000L);
                return;
            }
            return;
        }
        UserError.Log.ueh(TAG, "Not Low predict alerting due to snooze: " + str);
    }

    public static void persistentHighAlert(Context context, boolean z, String str) {
        int i;
        if (!z) {
            ((NotificationManager) context.getSystemService("notification")).cancel(13);
            UserNotification.DeleteNotificationByType("persistent_high_alert");
            return;
        }
        if (Pref.getLong("alerts_disabled_until", 0L) < JoH.tsl() && Pref.getLong("high_alerts_disabled_until", 0L) < JoH.tsl()) {
            try {
                i = Integer.parseInt(Pref.getString("persistent_high_repeat_mins", "20"));
            } catch (NumberFormatException unused) {
                UserError.Log.e(TAG, "Invalid snooze time for persistent high");
                i = 20;
            }
            if (i < 1) {
                i = 1;
            }
            if (i > 1440) {
                i = 1440;
            }
            OtherAlert(context, "persistent_high_alert", str, 13, "bgPersistentHighChannel", false, i * 60);
            if (Pref.getBooleanDefaultFalse("speak_alerts") && JoH.pratelimit("persist-high-speak", 1800)) {
                SpeechUtil.say(str, 4000L);
                return;
            }
            return;
        }
        UserError.Log.ueh(TAG, "Not persistent high alerting due to snooze: " + str);
    }

    public static void RiseDropAlert(Context context, boolean z, String str, String str2, int i) {
        if (z) {
            OtherAlert(context, str, str2, i, "bgRiseDropChannel", false, 21474L);
        } else {
            ((NotificationManager) context.getSystemService("notification")).cancel(i);
            UserNotification.DeleteNotificationByType(str);
        }
    }

    private static void OtherAlert(Context context, String str, String str2, int i, String str3, boolean z, long j) {
        OtherAlert(context, str, str2, str2, i, str3, z, j);
    }

    private static void OtherAlert(Context context, String str, String str2, String str3, int i, String str4, boolean z, long j) {
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String string = defaultSharedPreferences.getString(str + "_sound", defaultSharedPreferences.getString("other_alerts_sound", "content://settings/system/notification_sound"));
        Boolean valueOf = Boolean.valueOf(defaultSharedPreferences.getBoolean("other_alerts_override_silent", false));
        UserError.Log.d(TAG, "OtherAlert called " + str + " " + str3 + " reraiseSec = " + j);
        UserNotification GetNotificationByType = UserNotification.GetNotificationByType(str);
        if (GetNotificationByType == null || GetNotificationByType.timestamp <= new Date().getTime()) {
            if (GetNotificationByType != null) {
                try {
                    GetNotificationByType.delete();
                } catch (NullPointerException unused) {
                }
                UserError.Log.d(TAG, "Delete");
            }
            UserNotification.create(str3, str, new Date().getTime() + (j * 1000));
            boolean z2 = i == 13 && Home.get_forced_wear() && bg_notifications_watch && bg_persistent_high_alert_enabled_watch;
            UserError.Log.d(TAG, "OtherAlert forced_wear localOnly=" + z2);
            NotificationCompat.Builder contentIntent = new NotificationCompat.Builder(context, str4).setVisibility(Pref.getBooleanDefaultFalse("public_notifications") ? 1 : 0).setSmallIcon(2131230884).setContentTitle(str2).setContentText(str3).setLocalOnly(z2).setStyle(new NotificationCompat.BigTextStyle().bigText(str3)).setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, (Class<?>) Home.class), 134217728));
            if (z) {
                Intent intent = new Intent(context, (Class<?>) SnoozeOnNotificationDismissService.class);
                intent.putExtra("alertType", str);
                intent.putExtra("raisedTimeStamp", JoH.tsl());
                contentIntent.setDeleteIntent(PendingIntent.getService(context, 0, intent, 134217728));
            }
            contentIntent.setVibrate(vibratePattern);
            contentIntent.setLights(-16711936, 300, 1000);
            if (AlertPlayer.notSilencedDueToCall()) {
                if (valueOf.booleanValue()) {
                    contentIntent.setSound(Uri.parse(string), 4);
                } else {
                    contentIntent.setSound(Uri.parse(string));
                }
            }
            NotificationManager notificationManager = (NotificationManager) context.getSystemService("notification");
            UserError.Log.ueh("Other Alert", str3);
            notificationManager.notify(i, XdripNotificationCompat.build(contentIntent));
            if (Pref.getBooleanDefaultFalse("pref_amazfit_enable_key") && Pref.getBooleanDefaultFalse("pref_amazfit_other_alert_enable_key")) {
                Amazfitservice.start("xDrip_Otheralert", str3, 30);
            }
            BroadcastEntry.sendAlert(str, str3);
        }
    }

    private void clearCalibrationRequest() {
        UserNotification lastCalibrationAlert = UserNotification.lastCalibrationAlert();
        if (lastCalibrationAlert != null) {
            lastCalibrationAlert.delete();
            notificationDismiss(2);
        }
    }

    private void clearDoubleCalibrationRequest() {
        UserNotification lastDoubleCalibrationAlert = UserNotification.lastDoubleCalibrationAlert();
        if (lastDoubleCalibrationAlert != null) {
            lastDoubleCalibrationAlert.delete();
            notificationDismiss(3);
        }
    }

    private void clearExtraCalibrationRequest() {
        UserNotification lastExtraCalibrationAlert = UserNotification.lastExtraCalibrationAlert();
        if (lastExtraCalibrationAlert != null) {
            lastExtraCalibrationAlert.delete();
            notificationDismiss(4);
        }
    }

    public static void start() {
        if (JoH.ratelimit("start-notifications", 10)) {
            JoH.startService(Notifications.class);
        }
    }

    public static void staticUpdateNotification() {
        try {
            JoH.startService(Notifications.class);
        } catch (Exception e) {
            UserError.Log.e(TAG, "Got exception in staticupdatenotification: " + e);
        }
    }
}