无法从 onBackgroundMessage 启动 Activity

Posted

技术标签:

【中文标题】无法从 onBackgroundMessage 启动 Activity【英文标题】:Unable to start Activity from onBackgroundMessage 【发布时间】:2021-07-24 07:55:41 【问题描述】:

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

最终在收到通知时尝试打开我的应用或显示全屏 Activity(想想电话)

目前只是尝试通过后台消息处理程序调用本地类来控制台登录

当我发送通知时收到此错误,你知道我做错了什么吗?我应该以不同的方式解决这个问题吗?

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());

...

MainActivity.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 中工作

【问题讨论】:

【参考方案1】:

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

    本地捕获消息 使用flutter-local-notifications 和流

我最终选择了解决方案 2,因为它提供了更好的平台支持并且不那么 hacky

我只会展示 android 实现

(选项 1)本地捕获消息

安装firebase-messaging

// 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 和流

安装flutter 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();
  
...

【讨论】:

以上是关于无法从 onBackgroundMessage 启动 Activity的主要内容,如果未能解决你的问题,请参考以下文章

Flutter Firebase 云消息传递:`onBackgroundMessage` 的用途是啥?

Flutter FCM onBackgroundMessage 处理程序给出空检查错误

FIREBASE_MESSAGING:当应用程序处于后台或终止时,onBackgroundMessage 不处理通知

Flutter onBackgroundMessage android myimage通知不起作用

在 Flutter 中,我们如何使用 Firebase Messaging onBackgroundMessage 创建通知,使用flutter_local_notifications?

Virtualbox虚机无法启动因断电