Flutter后台服务插件flutter_background_service_android的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter后台服务插件flutter_background_service_android的使用

简介

flutter_background_service_androidflutter_background_service 插件的 Android 实现。通过使用 flutter_background_service,你可以在 Flutter 应用中轻松地创建和管理后台服务。

使用方法

添加依赖

首先,在你的 pubspec.yaml 文件中添加 flutter_background_service 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_background_service: ^0.2.0

然后运行 flutter pub get 来安装依赖。

初始化后台服务

在你的主入口文件(通常是 main.dart)中初始化后台服务:

import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final service = FlutterBackgroundService();
  await service.configure(
    androidConfiguration: AndroidConfiguration(
      // this will be 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 be executed when app is in foreground in separated isolate
      onForeground: onIosForeground,

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

  runApp(MyApp());
}

// to ensure this executed
// run isolate in background
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  // Only available for flutter 3.0.0 and later
  DartPluginRegistrant.ensureInitialized();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    service.stopSelf();
  });

  // bring to foreground
  Timer.periodic(const Duration(seconds: 1), (timer) async {
    if (service is AndroidServiceInstance) {
      service.setForegroundNotificationInfo(
        title: "My Background Service",
        content: "Running in background",
      );
    }
  });
}

@pragma('vm:entry-point')
void onIosForeground(ServiceInstance service) {
  // you can handle iOS foreground event here
}

@pragma('vm:entry-point')
void onIosBackground(ServiceInstance service) {
  // you can handle iOS background event here
}

创建UI

在你的 Flutter 应用中创建一个简单的 UI 来控制后台服务:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Background Service'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  FlutterBackgroundService().invoke('setAsForeground');
                },
                child: Text('Start Foreground Service'),
              ),
              ElevatedButton(
                onPressed: () {
                  FlutterBackgroundService().invoke('setAsBackground');
                },
                child: Text('Start Background Service'),
              ),
              ElevatedButton(
                onPressed: () {
                  FlutterBackgroundService().invoke('stopService');
                },
                child: Text('Stop Service'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

配置AndroidManifest.xml

确保在你的 AndroidManifest.xml 文件中添加必要的权限和配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <application
        android:label="yourapp"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|presentation"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <service
            android:name="dev.flutter.plugins.backgroundservice.BackgroundService"
            android:exported="false"
            android:enabled="true">
            <intent-filter>
                <action android:name="dev.flutter.plugins.backgroundservice.BackgroundService" />
            </intent-filter>
        </service>
    </application>

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
</manifest>

运行应用

现在你可以运行你的 Flutter 应用,点击按钮来启动和停止后台服务。

总结

通过 flutter_background_serviceflutter_background_service_android,你可以在 Flutter 应用中轻松实现后台服务功能。希望这个示例能帮助你快速上手并实现你的需求。如果有任何问题或需要进一步的帮助,请随时提问。


更多关于Flutter后台服务插件flutter_background_service_android的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter后台服务插件flutter_background_service_android的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_background_service_android插件的详细代码示例。这个插件允许你在Android设备上运行后台服务,执行长时间运行的任务,比如位置追踪、数据同步等。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加flutter_background_service_android依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_background_service_android: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Android权限

android/app/src/main/AndroidManifest.xml中添加必要的权限,例如访问网络、位置等权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <!-- 其他配置 -->

</manifest>

3. 初始化后台服务

在你的Flutter项目中,初始化并使用flutter_background_service_android插件。以下是一个完整的示例,包括启动、配置和停止后台服务。

import 'package:flutter/material.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';

void main() {
  runApp(MyApp());
  // 初始化后台服务
  FlutterBackgroundServiceAndroid.initialize();
}

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Background Service Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  // 启动后台服务
                  startBackgroundService();
                },
                child: Text('Start Background Service'),
              ),
              ElevatedButton(
                onPressed: () {
                  // 停止后台服务
                  stopBackgroundService();
                },
                child: Text('Stop Background Service'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void startBackgroundService() {
    FlutterBackgroundServiceAndroid.start(
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'your_channel_id',
        channelName: 'Your Channel Name',
        channelDescription: 'Your Channel Description',
        ongoing: true,
        importance: Importance.high,
        priority: Priority.high,
        title: 'Background Service',
        content: 'Running in the background',
        color: Colors.blue,
      ),
      task: () async {
        // 在这里执行后台任务,例如位置追踪、数据同步等
        while (true) {
          print('Background service is running...');
          await Future.delayed(Duration(seconds: 10)); // 模拟长时间运行的任务
        }
      },
    );
  }

  void stopBackgroundService() {
    FlutterBackgroundServiceAndroid.stop();
  }
}

4. 创建通知渠道(如果需要)

从Android Oreo(API级别26)开始,所有通知都必须分配到一个通知渠道。如果你的应用目标版本是Android Oreo或更高版本,你需要在你的Flutter应用中创建通知渠道。不过,flutter_background_service_android插件已经抽象了这部分,你只需在AndroidNotificationOptions中提供必要的渠道信息即可。

5. 注意事项

  • 确保你已经处理了所有必要的权限请求,特别是位置权限和后台运行权限。
  • 长时间运行的任务可能会消耗大量电池和内存,因此请确保你的后台服务是高效且必要的。
  • 对于生产应用,请考虑使用更健壮的错误处理和日志记录。

通过上述步骤,你应该能够在Flutter应用中成功集成并使用flutter_background_service_android插件来运行后台服务。

回到顶部