cobi_flutter_service 1.0.2 copy "cobi_flutter_service: ^1.0.2" to clipboard
cobi_flutter_service: ^1.0.2 copied to clipboard

PlatformAndroid

An implementation of services for Flutter.

example/lib/main.dart

import 'dart:async';
import 'dart:isolate';

import "package:flutter/material.dart";

import "package:cobi_flutter_service/cobi_flutter_service.dart";

// This is invoked on the background isolate
void serviceRunner(SendPort sendPort, ReceivePort recPort) {
  debugPrint("service runner invoked");
  int counter = 0;
  
  Timer timer = Timer.periodic(Duration(seconds: 1), (timer) {
    debugPrint("counter: ${counter}");
    counter++;
  });
  
  // Declare notification contents
  CobiNotificationData notificationData = CobiNotificationData(
    title: "My background service",
    subtitle: "running",
    icon: CobiIconData(
      // this is the autogenerated flutter icon
      name: "ic_launcher",
      type: "native",
      subtype: "mipmap"
      // This can also be an icon from flutter's assets
      // Note: Make sure it follows the Android guidelines for notificatoin icons, e.g. transparent background
      // name: "images/ic_launcher.png",
      // type: "asset"
    ),
    showQuitAction: true,
    quitActionCaption: "Stop",
    actions: [
      CobiNotificationAction(
        name: "sendData",
        caption: "Send Data"
      ),
      CobiNotificationAction(
        name: "runExampleFunction",
        caption: "Run Example Function"
      )
    ]
  );
  // Set notification contents
  // This is necessary if you use the service as a foreground service on Android SDK >= 26
  CobiFlutterService.instance.setNotificationData(notificationData);
  
  recPort.listen((message) {
    // stop the periodic execution
    if (message == "stop") {
      timer.cancel();
      debugPrint("Timer cancelled");
    }
    
    if (message is Map) {
      // this is a custom action
      if (message["action"] != null) {
        if (message["action"] == "runExampleFunction") {
          exampleFunction();
        }
        // another custom action to be executed and sends some data to the UI isolate
        if (message["action"] == "sendData") {
          Map<String, dynamic> answer = {
            "action": "sendData",
            "data": {"msg":["Hello", "World"]}
          };
          sendPort.send(answer);
        }
      }
      
      // this is a builtin event to notify the isolate that it receives some data from the UI isolate
      if (message["event"] != null) {
        if (message["event"] == "onReceiveData") {
          debugPrint("data received: " + message["data"].toString());
        }
      }
    }
  });
}

void exampleFunction() {
  debugPrint("exampleFunction invoked");
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  CobiFlutterService.instance.initService(serviceRunner, false)
  .then((_) async {
    await CobiFlutterService.instance.startService();
    runApp(MyApp());
  });
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  
  _MyAppState() {
    CobiFlutterService.instance.onServiceStateChanged.last
    .then((value) {
      setState(() {
        _isRunning = value ?? false;
      });
    });
    CobiFlutterService.instance.onServiceStateChanged.listen((isRunning) {
      debugPrint("isRunning: ${isRunning ?? "false"}");
      setState(() {
        _isRunning = isRunning ?? false;
      });
    });
    
    CobiFlutterService.instance.onDataReceived.listen((data) {
      debugPrint("onDataReceived: " + data.toString());
      setState(() {
        _data = data;
      });
    });
    
    CobiFlutterService.instance.getAutostartOnBoot()
    .then(_setAutostartState);
  }
  
  @override
  void initState() {
    super.initState();
    
    CobiFlutterService.instance.getAutostartOnBoot()
    .then(_setAutostartState);
  }
  
  _setAutostartState(bool value) {
    debugPrint("autostart: $value");
    setState(() {
      _autostart = value;
    });
  }
  
  bool _isRunning = false;
  dynamic _data;
  bool _autostart = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("CobiFlutterService example app"),
        ),
        body: Container(
          padding: const EdgeInsets.all(0.0),
          child: ListView(
            padding: const EdgeInsets.all(20.0),
            children: [
              ElevatedButton(
                child: Text("Start service"),
                onPressed: _isRunning ? null : () async {
                  await CobiFlutterService.instance.startService();
                },
              ),
              ElevatedButton(
                child: Text("Stop service"),
                onPressed: _isRunning ? () async {
                  await CobiFlutterService.instance.stopService();
                } : null,
                
              ),
              ElevatedButton(
                child: Text("Toggle foreground"),
                onPressed: _isRunning ? () async {
                  bool foreground = (await CobiFlutterService.instance.getForegroundMode()) ?? false;
                  foreground = !foreground;
                  await CobiFlutterService.instance.setForegroundMode(foreground);
                } : null,
              ),
              ElevatedButton(
                child: Text("Run example function"),
                onPressed: _isRunning ? () async {
                  bool result = (await CobiFlutterService.instance.executeAction("runExampleFunction"))!;
                  debugPrint("Function executed successfully: ${result}");
                } : null,
              ),
              ElevatedButton(
                child: Text("Send data"),
                onPressed: _isRunning ? () async {
                  await CobiFlutterService.instance.sendData({"msg":["Hello", "World"]});
                } : null,
              ),
              ElevatedButton(
                child: Text("Toggle autostart on boot"),
                onPressed: () async {
                  bool autostart = (await CobiFlutterService.instance.getAutostartOnBoot());
                  autostart = !autostart;
                  CobiFlutterService.instance.setAutostartOnBoot(autostart);
                  setState(() {
                    _autostart = autostart;
                  });
                }
              ),
              Text("service running: " + _isRunning.toString()),
              Text("Received data: " + (_data != null ? _data.toString() : "No data received")),
              Text("Autostart on boot: " + _autostart.toString()),
            ]
          ),
        ),
      ),
    );
  }
}