Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
8.8 kB
6
Indexable
Working code without bg running


main.dart-----------

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:udp/udp.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'dart:io';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UdpCommunicator(),
    );
  }
}

class UdpCommunicator extends StatefulWidget {
  @override
  _UdpCommunicatorState createState() => _UdpCommunicatorState();
}

class _UdpCommunicatorState extends State<UdpCommunicator> {
  String receivedMessage = 'Waiting for message...';
  String localIp = 'Unknown';
  TextEditingController ip = TextEditingController();
  TextEditingController message = TextEditingController();
  final String targetIp =
      '192.168.0.116'; // Replace with the receiver's IP address
  final int targetPort = 8080; // Port number

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  @override
  void initState() {
    super.initState();
    initNotifications();
    load();
    receiveUdpMessage();
  }

  static onDidReceiveLocalNotification(
      int id, String? title, String? body, String? payload) async {
    // display a dialog with the notification details, tap ok to go to another page
    showDialog(
      context: Get.context!,
      builder: (BuildContext context) => CupertinoAlertDialog(
        title: Text(title ?? ''),
        content: Text(body ?? ''),
        actions: [
          CupertinoDialogAction(
            isDefaultAction: true,
            child: Text('Ok'),
            onPressed: () async {
              Navigator.of(context, rootNavigator: true).pop();
              await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => Scaffold(body: Text(payload ?? '')),
                ),
              );
            },
          )
        ],
      ),
    );
  }

  void initNotifications() async {
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('ic_launcher');
    final DarwinInitializationSettings initializationSettingsDarwin =
        DarwinInitializationSettings(
            onDidReceiveLocalNotification: onDidReceiveLocalNotification);

    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsDarwin,
            macOS: null);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  load() async {
    localIp = await getLocalIpAddress();
  }

  Future<String> getLocalIpAddress() async {
    final info = NetworkInfo();
    String localIp = await info.getWifiIP() ?? '';
    print(localIp);
    return localIp;
  }

  Future<void> sendUdpMessage(String message) async {
    var sender = await UDP.bind(Endpoint.any());
    var data = message.codeUnits;
    await sender.send(data,
        Endpoint.unicast(InternetAddress(targetIp), port: Port(targetPort)));
    sender.close();
  }

  Future<void> receiveUdpMessage() async {
    var receiver = await UDP
        .bind(Endpoint.any(port: Port(8080))); // Listen on the same port

    receiver.asStream().listen((datagram) {
      if (datagram != null) {
        setState(() {
          receivedMessage = String.fromCharCodes(datagram.data);
        });
        showNotification(receivedMessage);
      }
    });
  }

  Future<void> showNotification(String message) async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails('your_channel_id', 'your_channel_name',
            channelDescription: 'your_channel_description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
        0, 'UDP Message Received', message, platformChannelSpecifics,
        payload: 'item x');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('UDP Communicator'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Local IP Address:',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              localIp,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            Text(
              'Target IP Address:',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              targetIp,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 40),
            Text(
              'Received Message:',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              receivedMessage,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 40),
            ElevatedButton(
              onPressed: () {
                sendUdpMessage('Hello from $localIp');
              },
              child: Text('Send UDP Message'),
            ),
          ],
        ),
      ),
    );
  }
}





------appdelegate.swift---------

import UIKit
import Flutter
import UserNotifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    private var udpListener: UdpListener?

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)

        // Set up the MethodChannel
        let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
        let methodChannel = FlutterMethodChannel(name: "com.beams_app.beams_app/service", binaryMessenger: controller.binaryMessenger)

        methodChannel.setMethodCallHandler { [weak self] (call, result) in
         print("Method called: \(call.method)") 
            if call.method == "startForegroundService" {
                print("Method 'startForegroundService' called")
                
                self?.startUdpListener()
                result("Service started")  // Acknowledge the call with a success message
            } else {
                print("Method not implemented: \(call.method)")
                result(FlutterMethodNotImplemented)
            }
        }

        // Register for push notifications (optional)
        registerForPushNotifications(application)

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    private func registerForPushNotifications(_ application: UIApplication) {
        UNUserNotificationCenter.current().delegate = self
        let options: UNAuthorizationOptions = [.alert, .sound, .badge]
        UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, error) in
            if let error = error {
                print("Error requesting push notification permissions: \(error)")
            } else {
                print("Push notification permission granted: \(granted)")
            }
        }
        application.registerForRemoteNotifications()
    }

    private func startUdpListener() {
    print("Attempting to start UDP Listener")  // Add this log
    if udpListener == nil {
        udpListener = UdpListener()
        udpListener?.startListening()
        print("UDP Listener started")
    } else {
        print("UDP Listener is already running")
    }
}

}




------info.plist-----

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>processing</string>
    <string>remote-notification</string>
</array>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app requires location access to retrieve the local IP address.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app requires location access to retrieve the local IP address.</string>
Leave a Comment