ekasetiawans / flutter_background_service

269 stars 189 forks source link

Stopping flutter ringtone #129

Closed sud4rm4n closed 2 years ago

sud4rm4n commented 2 years ago

Gan, How to stop FlutterRingtonePlayer.playAlarm(); that triggered from background

`import 'dart:convert'; import 'dart:async'; import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:apps2/mapTrackingPage.dart'; import 'package:cron/cron.dart'; import 'package:flutter/material.dart'; import 'package:flutter_ringtone_player/flutter_ringtone_player.dart'; import 'package:http/http.dart' as http; import 'package:fluttertoast/fluttertoast.dart'; import 'package:apps2/adminPage.dart'; import 'package:apps2/memberPage.dart'; import 'package:apps2/homePage.dart'; import 'package:apps2/alarmPage.dart'; import 'package:apps2/lockPage.dart'; import 'package:apps2/trackLocationPage.dart'; import 'package:apps2/historyPage.dart'; import 'package:vibration/vibration.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:flutter_background_service_ios/flutter_background_service_ios.dart'; import 'package:shared_preferences/shared_preferences.dart';

void main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); }

Future initializeService() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( // this will executed when app is in foreground or background in separated isolate onStart: onStart,

  // auto start service
  autoStart: true,
  isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
  // auto start service
  autoStart: true,

  // this will executed when app is in foreground in separated isolate
  onForeground: onStart,

  // you have to enable background fetch capability on xcode project
  onBackground: onIosBackground,
),

); }

void onIosBackground() { WidgetsFlutterBinding.ensureInitialized(); print('FLUTTER BACKGROUND FETCH'); }

void onStart() { WidgetsFlutterBinding.ensureInitialized(); if (Platform.isIOS) FlutterBackgroundServiceIOS.registerWith(); if (Platform.isAndroid) FlutterBackgroundServiceAndroid.registerWith(); final service = FlutterBackgroundService(); service.onDataReceived.listen((event) { fld_imei = event!["fld_imei"]; if (event["action"] == "alarm_stop") { FlutterRingtonePlayer.stop(); }

});

var cron = new Cron(); cron.schedule(new Schedule.parse('/1 *'), () async { _checkAlarm(); }); }

Future _checkAlarm() async { // final prefs = await SharedPreferences.getInstance(); // prefs.reload(); final response = await http.post(Uri.parse("http://xxxxxxxxxxxx/gpstrack/checkAlarm.php"), body: { "fld_imei": fld_imei, });

var res = json.decode(response.body); print(res); if(res.length > 0) { await http.post(Uri.parse("http://xxxxxxxxxxx/gpstrack/insertLog.php"), body: { "flag": "1", "message" : res[0]['engine'], }); if(res[0]['engine'] == "1") { await http.post(Uri.parse("http://xxxxxxxxxxxx/gpstrack/insertLog.php"), body: { "flag": "2", "message" : "Alarm has been fired at ${DateTime.now()}", }); print("Alarm fired"); FlutterRingtonePlayer.playAlarm();

 Vibration.vibrate(pattern: [500, 1000, 500, 1000,500, 1000, 500, 1000,500, 1000, 500, 1000,500, 1000, 500, 1000], intensities: [1, 255]);
 await Future.delayed(Duration(milliseconds: 5000));
 Vibration.vibrate(pattern: [500, 1000, 500, 1000,500, 1000, 500, 1000,500, 1000, 500, 1000,500, 1000, 500, 1000], intensities: [1, 255]);
 //showAlertDialog(context);
   }

} var error = 0; return error; }

String username = ''; String userid = ''; String userfullnm = ''; String fld_imei = ''; String fld_simcard = ''; class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), routes:<String,WidgetBuilder> { '/AdminPage' : (BuildContext context) => new AdminPage( username: username, userid: userid, ), '/MemberPage' : (BuildContext context) => new MemberPage(), '/AlarmPage' : (BuildContext context) => new AlarmPage(), '/LockPage' : (BuildContext context) => new LockPage(), '/HistoryPage' : (BuildContext context) => new HistoryPage(), '/MapTrackingPage' : (BuildContext context) => new MapTrackingPage(),

    '/HomePage' : (BuildContext context) => new HomePage(
      username: username,
      userid: userid,
      userfullnm: userfullnm,
      fld_imei: fld_imei,
    ),
    '/TrackLocationPage' : (BuildContext context) => new TrackLocationPage(
      username: username,
    ),
    '/MyHomePage' : (BuildContext context) =>new MyHomePage(title: 'Home'),

  }
);

} }

class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State createState() => _MyHomePageState(); }

class _MyHomePageState extends State {

bool _isHidePassword = true; void _togglePassword() { setState(() { _isHidePassword = !_isHidePassword; }); } TextEditingController user = new TextEditingController(); TextEditingController pass = new TextEditingController();

Future _login() async { final prefs = await SharedPreferences.getInstance(); final response = await http.post(Uri.parse("http://xxxxxxxxxxxx/gpstrack/login2.php"), body: { "username": user.text, "password": pass.text, }); var datauser = json.decode(response.body); if (datauser.length == 0) { setState(() { tampil(); }); } else { Navigator.pushReplacementNamed(context, '/HomePage');

  fld_imei = datauser[0]['fld_imei'];
  final myData = json.encode({
    'fld_imei': fld_imei,
  });
  prefs.setString('myData', myData);

  FlutterBackgroundService()
      .sendData({"fld_imei": fld_imei});

  setState(() {
    username = datauser[0]['fld_usernm'];
    userid = datauser[0]['fld_userid'];
    userfullnm = datauser[0]['fld_userfullnm'];
    fld_imei = datauser[0]['fld_imei'];
    fld_simcard = datauser[0]['fld_simcard'];
  });

}
return datauser;

}

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Login"), automaticallyImplyLeading: true, leading: IconButton(icon: Icon(Icons.arrow_back),onPressed: () => Navigator.pop(context, false), ), ), body: Padding( padding: const EdgeInsets.fromLTRB(25, 50, 25, 0), child: Center( child: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(18, 0, 18, 18), child: TextField( controller: user, decoration: InputDecoration( //hintText: 'Username'

                fillColor: Colors.lightGreen[40],
                filled: true,
                prefixIcon: Icon(
                  Icons.person,
                  color: Colors.blue,
                ),
                prefixStyle: TextStyle(
                    color: Colors.blue, fontWeight: FontWeight.w600),
                labelText: "Username",
                hintText: 'Username anda',
                hintStyle: TextStyle(
                    color: Colors.black, fontWeight: FontWeight.w200),
                labelStyle: TextStyle(
                    color: Colors.blue, fontWeight: FontWeight.w600),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(18, 0, 18, 0),
            child: TextField(
              controller: pass,
              obscureText: _isHidePassword,
              decoration: InputDecoration(
                //hintText: 'Password'

                fillColor: Colors.lightGreen[40],
                filled: true,
                prefixIcon: Icon(
                  Icons.lock,
                  color: Colors.blue,
                ),
                prefixStyle: TextStyle(
                    color: Colors.blue, fontWeight: FontWeight.w600),
                labelText: "Password",
                hintText: 'Pawssord anda',
                hintStyle: TextStyle(
                    color: Colors.black, fontWeight: FontWeight.w200),
                labelStyle: TextStyle(
                    color: Colors.blue, fontWeight: FontWeight.w600),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
                suffixIcon: GestureDetector(
                  onTap: () {
                    _togglePassword();
                  },
                  child: Icon(
                    _isHidePassword
                        ? Icons.visibility_off
                        : Icons.visibility,
                    color: _isHidePassword ? Colors.grey : Colors.blue,
                  ),
                ),
                isDense: true,

              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
            child: RaisedButton(
              child: Text(
                "Login",
                style: TextStyle(fontSize: 20),
              ),
              padding: EdgeInsets.fromLTRB(60, 10, 60, 10),
              textColor: Colors.white,
              color: Colors.blue,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(16.0))),
              onPressed: () {
                _login();
              },
            ),
          ),
        ],
      ),
    ),
  ),
);

}

void tampil() { Fluttertoast.showToast( msg: "LOGIN GAGAL", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, timeInSecForIosWeb: 1, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); } } `

sud4rm4n commented 2 years ago

Solved ...