3

刚刚创建了一个新的 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)

主要.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 clean flutter run
  • 在手机上卸载/重新安装应用程序
  • 将 Android Gradle 插件版本恢复为 3.5.1
  • 添加android/app/src/proguard-rules.pro-keep class androidx.lifecycle.DefaultLifecycleObserver
  • 使用与我在清单中设置的频道不同的频道
  • platform.invokeMethod()通过在应用程序内单击按钮,它确实可以在应用程序 UI 中工作
4

1 回答 1

1

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

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

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

我只会展示 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和流

安装颤振部门

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

FCM 消息处理程序main.dart

// 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();
  }
...
于 2021-05-03T08:13:12.000 回答