Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
7.8 kB
0
Indexable
Never
import 'dart:async';
import 'dart:ffi';
import 'package:alarm/alarm.dart';
import 'package:alarm_example/screens/ring.dart';
import 'package:alarm_example/screens/secound.dart';
import 'package:alarm_example/screens/slotselection.dart';
import 'package:alarm_example/utils/user_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

class MyhomeScreen extends StatefulWidget {
  const MyhomeScreen({Key? key}) : super(key: key);

  @override
  State<MyhomeScreen> createState() => _MyhomeScreenState();
}

class _MyhomeScreenState extends State<MyhomeScreen> {
  late List<AlarmSettings> alarms;

  static StreamSubscription<AlarmSettings>? subscription;
  int checkingofi = 0;

  @override
  void initState() {
    super.initState();

    if (Alarm.android) {
      checkAndroidNotificationPermission();
      setState(() => {});
    }
    loadAlarms();
   

    subscription ??= Alarm.ringStream.stream.listen(
      (alarmSettings) {
        navigateToRingScreen(alarmSettings);
      },
    );
  }

  Future<void> checkAndroidNotificationPermission() async {
    final status = await Permission.notification.status;
    if (status.isDenied) {
      alarmPrint('Requesting notification permission...');
      final res = await Permission.notification.request();
      alarmPrint(
        'Notification permission ${res.isGranted ? '' : 'not '}granted.',
      );
    }
  }

  void loadAlarms() {
    setState(() {
      alarms = Alarm.getAlarms();
      alarms.sort((a, b) => a.dateTime.isBefore(b.dateTime) ? 0 : 1);
      print("listen 5 : ${alarms.length}");
      print('check ittt ${alarms}');
      newfunc();
    });
  }

  void newfunc() async {
    final checkfirsttime = UserPreferences.getBool(UserPrefKeys.isNotFirstTime);
    int timesavedbyuser =
        UserPreferences.getInt(UserPrefKeys.timesavedbyuser) ?? 0;
    final savedTime = DateTime.fromMillisecondsSinceEpoch(timesavedbyuser);
    checkingofi = UserPreferences.getInt(UserPrefKeys.ivalueofloop) ?? 0;
    int checklastdate =
        UserPreferences.getInt(UserPrefKeys.confirmationcall) ?? 0;
    final savedlastdate = DateTime.fromMillisecondsSinceEpoch(checklastdate);

    DateTime dateTimecurrent = DateTime(
      DateTime.now().year,
      DateTime.now().month,
      DateTime.now().day,
      savedTime.hour,
      savedTime.minute,
    );

    DateTime dateTimenow = DateTime.now();
    DateTime lastUpdatedDate = DateTime.fromMillisecondsSinceEpoch(
        UserPreferences.getInt(UserPrefKeys.lastUpdatedDate) ?? 0);
    var dateTimeaftertendays = dateTimecurrent.add(const Duration(days: 10));

    if (checkfirsttime) {
      print('$lastUpdatedDate');
      if (dateTimenow.isBefore(dateTimeaftertendays)) {
        if (checkingofi == 1) {
          print('afv');
          getSavedTImeAndSetAlarmForTenDays();
          checkingofi = 2;
          changeValueOfI(checkingofi);
        } else if (checkingofi >= 2) {
          if (dateTimenow.day != lastUpdatedDate.day && checkingofi > 1) {
            print('lastUpdatedDate $lastUpdatedDate.day');
            print('dateTimenow $dateTimenow.day');
            checkingofi = checkingofi + 1;
            print('checkingofi value $checkingofi');
            changeValueOfI(checkingofi);
          }
        }
        lastUpdatedDate = dateTimenow;
        UserPreferences.setInt(
            UserPrefKeys.lastUpdatedDate, dateTimenow.millisecondsSinceEpoch);
        setState(() {});
      }

      if (dateTimeaftertendays == dateTimenow ||
          dateTimenow.isAfter(dateTimeaftertendays)) {
        getSavedTImeAndSetAlarmForTenDays();
        checkingofi = 2;
        changeValueOfI(checkingofi);

        lastUpdatedDate = dateTimenow;
        UserPreferences.setInt(
            UserPrefKeys.lastUpdatedDate, dateTimenow.millisecondsSinceEpoch);
        setState(() {});
      }
    }
  }

  //yeh kaam kar gya ha!!
  void getSavedTImeAndSetAlarmForTenDays() async {
    int timesavedbyuser =
        UserPreferences.getInt(UserPrefKeys.timesavedbyuser) ?? 0;
    final savedTime = DateTime.fromMillisecondsSinceEpoch(timesavedbyuser);

    for (var i = 1; i < 11; i++) {
      DateTime dateTimecurrentnew = DateTime(
        DateTime.now().year,
        DateTime.now().month,
        DateTime.now().day,
        savedTime.hour,
        savedTime.minute,
      ).add(Duration(days: i));

      print('inside -- $dateTimecurrentnew');

      final alarmSettings = AlarmSettings(
        id: DateTime.now().millisecondsSinceEpoch % 10000,
        dateTime: dateTimecurrentnew,
        assetAudioPath: 'assets/marimba.mp3',
        notificationTitle: 'Alarm ringing !',
        notificationBody:
            'Periodic alarm ringing, day ${dateTimecurrentnew.day}.',
        enableNotificationOnKill: true,
        androidFullScreenIntent: true,
        vibrate: true,
        loopAudio: true,
      );
      await Alarm.set(
        alarmSettings: alarmSettings,
      ); // If the alarm was already set, it will just override it
    }
  }

  void saveAlarm({
    AlarmSettings? settings,
    required DateTime dateTime,
  }) {
    final alarm = buildAlarmSettings(
      settings: settings,
      dateTime: dateTime,
    );
    Alarm.set(alarmSettings: alarm);
  }

  AlarmSettings buildAlarmSettings({
    AlarmSettings? settings,
    required DateTime dateTime,
  }) {
    final id = settings == null
        ? DateTime.now().millisecondsSinceEpoch % 10000
        : settings.id;

    final alarmSettings = AlarmSettings(
      id: id,
      dateTime: dateTime,
      assetAudioPath: 'assets/marimba.mp3',
      notificationTitle: 'Alarm example',
      notificationBody: 'Your alarm ($id) is ringing',
      enableNotificationOnKill: true,
      androidFullScreenIntent: true,
      vibrate: true,
      loopAudio: true,
    );
    return alarmSettings;
  }

  Future<void> navigateToRingScreen(AlarmSettings alarmSettings) async {
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
            ExampleAlarmRingScreen(alarmSettings: alarmSettings),
      ),
    );
    loadAlarms();
  }

  void changeValueOfI(int newValue) {
    UserPreferences.setInt(UserPrefKeys.ivalueofloop, newValue);
    final abc = UserPreferences.setInt(UserPrefKeys.ivalueofloop, newValue);
    print('$abc');

    setState(() {
      checkingofi = newValue;
    });
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Mehar'),
        ),
        body: ListView(
          children: [
            Text(' value of i - $checkingofi'),
            ListTile(
              title: const Text('ALARM TILE'),
              onTap: () {
                final isNotFirst =
                    UserPreferences.getBool(UserPrefKeys.isNotFirstTime);

                if (isNotFirst) {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const SecoundScreen(),
                    ),
                  );
                } else {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const TimeSlotSelectionScreen(),
                    ),
                  );
                }
              },
            ),
          ],
        ));
  }
}
Leave a Comment