Flutter后台消息处理插件flutter_background_messenger的使用
Flutter后台消息处理插件flutter_background_messenger
的使用
特性
- 在Flutter应用中发送短信
- 处理短信权限
- 背景消息发送能力
开始使用
在你的包的 pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter_background_messenger: ^0.0.1
平台特定设置
Android
- 在你的
AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
- 确保你的
minSdkVersion
设置为21或更高版本。在你的android/app/build.gradle
文件中进行配置:
android {
...
defaultConfig {
...
minSdkVersion 21
}
}
使用方法
要发送短信,可以使用以下代码:
import 'package:flutter_background_messenger/flutter_background_messenger.dart';
class MessagingExample {
final messenger = FlutterBackgroundMessenger();
Future<void> sendSMS() async {
try {
final success = await messenger.sendSMS(
phoneNumber: '+1234567890',
message: 'Hello from Flutter Background Messenger!',
);
if (success) {
print('SMS sent successfully');
} else {
print('Failed to send SMS');
}
} catch (e) {
print('Error sending SMS: $e');
}
}
}
示例代码
以下是完整的示例代码:
import 'package:flutter/material.dart';
import 'package:flutter_background_messenger/flutter_background_messenger.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _messenger = FlutterBackgroundMessenger();
final _phoneController = TextEditingController();
final _messageController = TextEditingController();
String _status = '';
Future<void> _sendSMS() async {
try {
final success = await _messenger.sendSMS(
phoneNumber: _phoneController.text,
message: _messageController.text,
);
setState(() {
_status = success ? 'SMS sent successfully!' : 'Failed to send SMS';
});
} catch (e) {
setState(() {
_status = 'Error: ${e.toString()}';
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('短信背景消息处理示例'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _phoneController,
decoration: const InputDecoration(
labelText: '电话号码',
hintText: '+1234567890',
),
keyboardType: TextInputType.phone,
),
const SizedBox(height: 16),
TextField(
controller: _messageController,
decoration: const InputDecoration(
labelText: '消息',
hintText: '请输入您的消息',
),
maxLines: 3,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _sendSMS,
child: const Text('发送短信'),
),
const SizedBox(height: 16),
Text(_status),
],
),
),
),
);
}
[@override](/user/override)
void dispose() {
_phoneController.dispose();
_messageController.dispose();
super.dispose();
}
}
更多关于Flutter后台消息处理插件flutter_background_messenger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter后台消息处理插件flutter_background_messenger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter中使用flutter_background_messenger
插件来处理后台消息的示例代码。flutter_background_messenger
插件允许应用在后台接收和处理消息,这在实现推送通知等功能时非常有用。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_background_messenger
依赖:
dependencies:
flutter:
sdk: flutter
flutter_background_messenger: ^x.y.z # 替换为最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,你需要配置Android和iOS项目以支持后台消息处理。这里主要展示如何在Android上进行配置(iOS的配置过程类似,但涉及不同的文件和方法)。
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.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
...>
<!-- Firebase Messaging Service -->
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- Background Messenger Service -->
<service
android:name="com.dexterous.flutterlocalnotifications.FlutterLocalNotificationService"
android:exported="false"/>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
创建Firebase Messaging Service
在android/app/src/main/kotlin/com/example/yourapp/
(或对应的Java目录)下创建一个名为MyFirebaseMessagingService.kt
的文件(如果是Java,则扩展名为.java
):
package com.example.yourapp
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
class MyFirebaseMessagingService : FlutterFirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// 处理接收到的消息
Log.d("FirebaseMessaging", "From: ${remoteMessage.from}")
// 调用Flutter后台消息处理
handleBackgroundMessage(remoteMessage.data)
}
private fun handleBackgroundMessage(data: Map<String, String>) {
FlutterEngineCache
.getInstance()
.get("my_engine_id") // 确保在FlutterActivity或FlutterFragment中设置了相同的engine ID
?.dartExecutor
?.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
) { result ->
// 发送消息到Flutter
val channel = FlutterEngineCache.getInstance().get("my_engine_id")?.dartExecutor?.binaryMessenger
?.getMessagingChannel()
channel?.invokeMethod("backgroundMessageHandler", data)
}
}
}
Flutter代码
在你的Flutter项目中,初始化flutter_background_messenger
并设置后台消息处理器:
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_background_messenger/flutter_background_messenger.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterBackgroundMessenger.initialize(
onBackgroundMessage: myBackgroundMessageHandler,
);
runApp(MyApp());
}
Future<void> myBackgroundMessageHandler(Map<String, dynamic> message) async {
// 处理后台消息
print("Background message: $message");
// 显示本地通知(可选)
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your_channel_id',
'Your Channel Name',
'Your Channel Description',
importance: Importance.max,
priority: Priority.high,
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics,
iOSPlatformChannelSpecifics,
);
await flutterLocalNotificationsPlugin.show(
0,
'Background Message',
'You have a new background message: ${message['body'] ?? 'No message body'}',
platformChannelSpecifics,
payload: 'item x',
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Background Messenger Demo'),
),
body: Center(
child: Text('Check your console for background messages.'),
),
),
);
}
}
注意事项
- Engine ID:确保在
FlutterActivity
或FlutterFragment
中设置了与FlutterEngineCache.getInstance().get("my_engine_id")
相同的engine ID。 - 通知权限:在应用启动时请求通知权限,并确保用户已授予权限。
- Firebase配置:确保你的Firebase项目已正确配置,包括在
google-services.json
中包含了所有必要的配置信息。
这个示例展示了如何在Flutter中使用flutter_background_messenger
插件来处理后台消息,并通过本地通知向用户显示消息内容。根据你的具体需求,你可能需要调整消息处理逻辑和通知显示方式。