mo-ah-dawood / fcm_config

10 stars 12 forks source link

how to handle notification while app is terminated #15

Closed AbdullahGaber closed 3 years ago

AbdullahGaber commented 3 years ago

``hello brother , when i click on notification while app is in background i can open a particular screen but while app is terminated i can't open particular Screen this is my code in main.dart file

Future<void> _firebaseMessagingBackgroundHandler(
    RemoteMessage notification) async {
  await Firebase.initializeApp();
  prefs = await SharedPreferences.getInstance();

  log('TOOKEN' + await FirebaseMessaging.instance.getToken());
  // log(message.data.toString(),);

  // log(message..toString(),);
  if (notification.data['model'] == 'order') {
    if (prefs.getString('user_type') == 'customer') {
      N.to(
        OrderHistoryDetailsScreen(
          orderId: notification.data['model_id'],
        ),
      );
    } else if (prefs.getString('user_type') == 'owner') {
      N.to(
        RequestDetailsScreen(
          requestId: notification.data['model_id'],
        ),
      );
    }
  } else if (notification.data['model'] == 'product') {
    if (prefs.getString('user_type') == 'customer') {
      N.to(
        ProductDetailsScreen(
          productId: notification.data['model_id'],
        ),
      );
    } else if (prefs.getString('user_type') == 'owner') {
      N.to(
        MyProductDetailsScreen(
          productId: notification.data['model_id'],
        ),
      );
    }
  } else if (notification.data['model'] == 'payment') {
    if (prefs.getString('user_type') == 'owner') {
      N.to(
        SubscriptionsScreen(),
      );
    }
  } else if (notification.data['model'] == 'home') {
    if (prefs.getString('user_type') == 'customer') {
      N.to(
        TabScreen(),
      );
    } else if (prefs.getString('user_type') == 'owner') {
      N.to(
        ProviderHomeScreen(),
      );
    }
  }

  // print("Handling a background message: ${message.data['model']}");
}

SharedPreferences prefs;

void main() async {
  // log('message');
  await FCMConfig.instance
      .init(
    onBackgroundMessage: _firebaseMessagingBackgroundHandler,
    alert: true,
    announcement: true,
    badge: true,
    displayInForeground: true,
    carPlay: false,
    criticalAlert: true,
    provisional: false,
    sound: true,
  )
      .then((value) {
    // FirebaseMessaging.instance.onTokenRefresh.listen((event) {});
  });
  WidgetsFlutterBinding.ensureInitialized();
  await Intercom.initialize('gypd03cb',
      iosApiKey: 'ios_sdk-bf99d566d7baa560cb0f02514951e4e217835d21',
      androidApiKey: 'android_sdk-fb0b9293fba93d7adbd31f729dd4a2a69b646d42');

  await localization.init();
  await Firebase.initializeApp();

  log('TOOKEN' + await FirebaseMessaging.instance.getToken());

  prefs = await SharedPreferences.getInstance();
  runApp(
    Phoenix(
      child: MyApp(),
    ),
  );
}

my AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.afran">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.VIBRATE"/>  
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

   <application
        android:label="afran_flutter"
        android:icon="@mipmap/launcher_icon" android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config" android:requestLegacyExternalStorage="true">

    <meta-data android:name="com.google.android.geo.API_KEY" 
    android:value="AIzaSyBbQpHFXEziURi4Q5RpDD5kEgfeJ6-3l3Q"/>        
        <activity android:name="com.yalantis.ucrop.UCropActivity" android:screenOrientation="portrait" android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <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>
            <intent-filter>
                <action android:name="NOTIFICATION_CLICK"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
            <intent-filter>
               <action android:name="android.intent.action.VIEW" />
               <category android:name="android.intent.category.DEFAULT" />
               <category android:name="android.intent.category.BROWSABLE" />
               <data
                 android:host="afran.sa"
                 android:pathPrefix="/"
                 android:scheme="https" />
            </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" />
    </application>
</manifest>

thanks brother

mo-ah-dawood commented 3 years ago

when app is terminated there is no event is fired instead you can get the notification opened the app await FCMConfig.instance.getInitialMessage();

AbdullahGaber commented 3 years ago

when app is terminated there is no event is fired instead you can get the notification opened the app await FCMConfig.instance.getInitialMessage();

Thanks for your reply I try it but still same

mo-ah-dawood commented 3 years ago

i think you has to try it in release mode as you can not debug the terminated app try to get the message in your main function after init fcm

void main() async{
  await   await FCMConfig.instance.init();
 /// there is no need for the next line,package call it for you
 /// await Firebase.initializeApp();
 var notification=await FCMConfig.instance.getInitialMessage();
 /// you may get here the screen you want to open and path it to MyApp as at this point no navigation
  runApp(
    Phoenix(
      child: MyApp(
         screen: /// your first screen
       ),
    ),
  );
}
AbdullahGaber commented 3 years ago

i think you has to try it in release mode as you can not debug the terminated app try to get the message in your main function after init fcm

void main() async{
  await   await FCMConfig.instance.init();
 /// there is no need for the next line,package call it for you
 /// await Firebase.initializeApp();
 var notification=await FCMConfig.instance.getInitialMessage();
 /// you may get here the screen you want to open and path it to MyApp as at this point no navigation
  runApp(
    Phoenix(
      child: MyApp(
         screen: /// your first screen
       ),
    ),
  );
}

thank you brother , you saved my life