无法从onBackgroundMessage启动"活动"



刚刚创建了一个新的Flutter应用

最终当我收到通知(想想电话(时,尝试打开我的应用程序或显示全屏活动

当前正在尝试控制台登录通过后台消息处理程序调用的本机类

当我发送通知时收到这个错误,你看到我做错了什么吗?有什么不同的方法可以让我处理这个问题吗?

D/FLTFireMsgReceiver(17161): broadcast received for message
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist,test-api, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist,test-api, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
I/flutter (17161): FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter (17161): MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.dev/battery)

main.dart

...
Future<void> backgroundHandler(RemoteMessage message) async {
const platform = const MethodChannel('samples.flutter.dev/battery');
String response = "";
try {
final int result = await platform.invokeMethod('getBatteryLevel');
response = "Response: $result";
} on PlatformException catch (e) {
response = "Failed to Invoke: '${e.message}'.";
}
print(response);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
...

主要活动.kt

class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
Log.i(">>BLOOP", "inside configureFlutterEngine")
GeneratedPluginRegistrant.registerWith(flutterEngine);
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
// Note: this method is invoked on the main thread
Log.i(">>BLOOP", "call looking for method: ${call.method}");
if(call.method == "getBatteryLevel") {
result.success(1);
} else {
result.notImplemented()
}
}
}
}

AndroidManifest.xml

...
</activity>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="samples.flutter.dev/battery" />
<!-- 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" />
</application>
</manifest>

我尝试过的东西:

  • flutter cleanflutter run
  • 在手机上卸载/重新安装应用程序
  • 将Android Gradle插件版本恢复到3.5.1
  • android/app/src/proguard-rules.pro-keep class androidx.lifecycle.DefaultLifecycleObserver相加
  • 使用与我在清单中设置的通道不同的通道
  • platform.invokeMethod()通过应用程序内部的按钮点击,它确实可以在应用程序UI中工作

我无法注册后台处理程序可以调用的本机MethodCall函数。相反,我找到了两个解决方案:

  1. 以本机方式捕获消息
  2. 使用flutter-local-notifications和流

我最终选择了解决方案2,因为它有更好的平台支持,而且不那么黑客

我只展示android实现

(选项1(以本机方式捕获消息

安装firebase消息

// android/app/build.gradle
...
dependencies {
...
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-messaging:21.1.0' <-- THIS ONE
}

创建后台服务

// android/app/src/main/kotlin/<project>/BackgroundService.kt
class BackgroundService: FirebaseMessagingService() {
// Function triggered when we receive a message (as specified in AndroidManifest.xml
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Waking the screen for 5 seconds and disabling keyguard
val km = baseContext.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val kl = km.newKeyguardLock("MyKeyguardLock")
kl.disableKeyguard()
val pm = baseContext.getSystemService(Context.POWER_SERVICE) as PowerManager
val wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE, TAG)
wakeLock.acquire(5000L)
// Create an intent to launch .MainActivity and start it as a NEW_TASK
val notificationIntent = Intent("android.intent.category.LAUNCHER")
notificationIntent
.setAction(Intent.ACTION_MAIN)
.setClassName("com.myapp", "com.myapp.MainActivity")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(notificationIntent)
}
}

注册权限和BackgroundService以接收firebase消息事件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp">
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
...
</activity>
<service android:name=".BackgroundService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>

(选项2(使用flutter-local-notifications和流

安装颤振deps

# pubspec.yaml
...
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.4
firebase_messaging: ^9.1.2
flutter_local_notifications: ^5.0.0+3
rxdart: ^0.26.0
...

注册权限

<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
...
<activity
...
android:showWhenLocked="true"
android:turnScreenOn="true">

main.dart中的顶级初始化

// We use this to `show` new notifications from the app (instead of from firebase)
// You'll want to be sending high priority `data` messages through fcm, not notifications
final FlutterLocalNotificationsPlugin localNotifications = FlutterLocalNotificationsPlugin();
// Uses rxdart/subjects to trigger showing a different page in your app from an async handler
final BehaviorSubject<String> selectNotificationSubject = BehaviorSubject<String>();

main.dart中的FCM消息处理程序

// handler function for when we receive a fcm message
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// build out and show notification using flutter-local-notifications
const AndroidNotificationDetails androidSpecifics = AndroidNotificationDetails(
"channel_id", "channel_name", "Test bed for all dem notifications",
importance: Importance.max, priority: Priority.max, fullScreenIntent: true, showWhen: true);
const NotificationDetails platformSpecifics = NotificationDetails(android: androidSpecifics);
// The notification id should be unique here
await localNotifications.show(DateTime.now().second, "Plain title", "Plain body", platformSpecifics,
payload: "item x");
}

main.dart中的入口点函数

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// if the notification launched the app then show alert page
final NotificationAppLaunchDetails launchDetails = await localNotifications.getNotificationAppLaunchDetails();
String initialRoute = launchDetails.didNotificationLaunchApp ?? false ? ShowAlert.routeName : Home.routeName;

// initialize `flutter-local-notifications`, app_icon needs to be added as a drawable resource
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings("app_icon");
final InitializationSettings initializationSettings = InitializationSettings(android: androidSettings);
await localNotifications.initialize(initializationSettings, onSelectNotification: (String payload) async {
// Will be called when activity is shown from notification, here we can trigger showing our alert page
initialRoute = ShowAlert.routeName;
selectNotificationSubject.add(payload);
});
// Catch firebase messages with our handler function, which will then build and show a notification
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(
MaterialApp(
initialRoute: initialRoute,
routes: <String, WidgetBuilder>{
Home.routeName: (_) => Home(),
ShowAlert.routeName: (_) => ShowAlert(),
},
),
);
}

main.dart中的主窗口小部件

// Needs to be stateful so we can use lifecycle methods for the notification stream changes and navigation
class Home extends StatefulWidget {
static const String routeName = "/home";
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
super.initState();
// when onSelectNotification is called, our new payload will trigger this function
selectNotificationSubject.stream.listen((String payload) async {
await Navigator.pushNamed(context, ShowAlert.routeName);
});
}
@override
void dispose() {
selectNotificationSubject.close();
super.dispose();
}
...

相关内容

  • 没有找到相关文章

最新更新