簡體   English   中英

在我的 flutter(android) 應用程序中 - Firebase 推送通知在一段時間后停止為每個用戶接收

[英]In my flutter(android) app - Firebase push notifications stop receiving after some time for every user

我有一個 Flutter 應用程序(適用於 android)使用 fcm 通知。 通知由服務器通過 fcm 管理。 一開始,所有前台、后台、已殺狀態都會收到通知。

但是一段時間后,應用程序停止顯示通知(前台,后台全部 - 根本沒有通知)對於某些用戶來說,它是在 5 天之后,大約 1,2 周,等等。

一段時間后,應用程序停止為每個用戶顯示通知(前台、后台)。 應用 Firebase 配置如下。

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.d.app_name">
  
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

   
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!-- End Alarm Manager -->

    <!-- Cleartext Traffic required by Flutter Espresso, do not use in production -->
    <!-- android:name="io.flutter.app.FlutterApplication" -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="app name"
        android:usesCleartextTraffic="true">

        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:windowSoftInputMode="adjustResize">
           
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme" />

            <meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="AIzaSyBeTjQD2nWGhgyiZPu2VqdxwRLfoeTwKdk" />
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            
          
            
        </activity>
        <!-- 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" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyBeTjQD2nWGhgyiZPu2VqdxwRLfoeTwKdk" />

        <!-- Start Alarm Manager -->
        <service
            android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmService"
            android:exported="false"
            android:permission="android.permission.BIND_JOB_SERVICE" />


        <receiver
            android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmBroadcastReceiver"
            android:exported="false" />
        <receiver
            android:name="dev.fluttercommunity.plus.androidalarmmanager.RebootBroadcastReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <!-- End Alarm Manager -->
    </application>
</manifest>

應用程序.kt

package com.d.app_name
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.view.FlutterMain
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService;

class Application : FlutterApplication(), PluginRegistrantCallback {

    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingBackgroundService.setPluginRegistrant(this);
        FlutterMain.startInitialization(this)
    }

    override fun registerWith(registry: PluginRegistry?) {
    }
} 

main.dart


final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  'This channel is used for important notifications.', // description
  importance: Importance.high,
);

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("message received");

  final payload = message.data;

  flutterLocalNotificationsPlugin.show(
      int.parse(payload["ID"]),
      payload["TYPE"] + " | " + payload["SITE_NAME"],
      payload["STATUS"] +
          " at " +
          payload["SITE_ID"] +
          "(" +
          payload["OCCURRED_TIME"] +
          ")",
      NotificationDetails(
        android: AndroidNotificationDetails(
            'Alarm', 'channel.name', 'channel.description',
            icon: 'mipmap/ic_launcher',
            playSound: true,
            sound: RawResourceAndroidNotificationSound('alarm_ring_sweet'),
            importance: Importance.max,
            onlyAlertOnce: true),
      ));

}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<NOCProvider>(create: (context) => NOCProvider())
      ],
      child: MaterialApp(
        initialRoute: '/splash',
        onGenerateRoute: AppRoute.Router.genarateRoute,
      ),
    );
  }
}

家.dart


class Home extends StatefulWidget {
  final PageContainer _pageContainer;

  Home(this._pageContainer);

  @override
  _HomeState createState() => _HomeState(this._pageContainer);
}

class _HomeState extends State<Home> with WidgetsBindingObserver {
  PageContainer pageContainer;
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  _HomeState(this.pageContainer);

  /// Create a [AndroidNotificationChannel] for heads up notifications
  static const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title
    'This channel is used for important notifications.', // description
    importance: Importance.high,
  );

  /// Initialize the [FlutterLocalNotificationsPlugin] package.
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  void initFirebaseReciver() async {
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      var provider = Provider.of<NOCProvider>(context, listen: false);
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      provider.getAllAlarm();

      final payload = message.data;
      flutterLocalNotificationsPlugin.show(
          int.parse(payload["ID"]),
          payload["TYPE"] + " | " + payload["SITE_NAME"],
          payload["STATUS"] +
              " at " +
              payload["SITE_ID"] +
              "(" +
              payload["OCCURRED_TIME"] +
              ")",
          NotificationDetails(
            android: AndroidNotificationDetails(
                channel.id, channel.name, channel.description,
                icon: 'mipmap/ic_launcher',
                playSound: true,
                sound: RawResourceAndroidNotificationSound('alarm_ring_sweet'),
                importance: Importance.max,
                onlyAlertOnce: true),
          ));

     
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      var provider = Provider.of<NOCProvider>(context, listen: false);
      //get notifications and save in hive and return
      provider.getAllAlarm();
    });
  }

  void callBack(PageContainer callBackPageContainer) {
    setState(() {
      pageContainer = callBackPageContainer;
    });
  }


  Future<void> _firebaseMessagingBackgroundHandler(
      RemoteMessage message) async {
    await Firebase.initializeApp();
  }

  void _onTokenRefresh(String token) {
    var provider = Provider.of<NOCProvider>(context, listen: false);

    provider.updateFcmTokenOnRefresh(token);
  }

  void _tokenUpdate() {
    var provider = Provider.of<NOCProvider>(context, listen: false);
    provider.saveFcmToken();
  }

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    _tokenUpdate(); //update token in db
    FirebaseMessaging.instance.onTokenRefresh.listen(_onTokenRefresh);
    AndroidAlarmManager.initialize();
    
    WidgetsBinding.instance.addObserver(this);
    initFirebaseReciver();
  }


  @override
  Widget build(BuildContext context) {
    var provider = Provider.of<NOCProvider>(context, listen: true);
    FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage message) {
      print('FirebaseMessaging.instance');
    });

    return Scaffold( ... );
  }
}

可能是什么問題? 我相信配置和代碼沒問題。 知道如何至少排除故障嗎?

問題在於 Firebase 后端。 Firebase 沒有向設備發送通知。 檢查了 Firebase 分析並發現了這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM