无法从 onBackgroundMessage 启动 Activity

Unable to start Activity from onBackgroundMessage

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

最终 尝试打开我的应用程序或显示全屏 Activity 当我收到通知(想想 phone 调用)

目前 只是尝试控制台登录通过后台消息处理程序调用的本机 class

当我发送通知时收到这个错误,你知道我做错了什么吗?我应该用不同的方法来处理这个问题吗?

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>

我尝试过的事情:

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

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

I ended up going with solution 2 due to better platform support and it being less 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();
  }
...