首页 > 解决方案 > 应用打开时无法收到 Fire-base 通知

问题描述

我正在制作一个接收通知的 android 应用程序。当应用程序关闭或在后台时我可以收到通知,但是当应用程序打开时我无法收到它,甚至看起来它没有通过 onMessageReceived 方法。我需要添加或编辑什么?这是清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="saleh.example.trail">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-library android:name="org.apache.http.legacy" android:required="false"/>



        <activity
            android:name=".Products_List"
            android:label="@string/title_activity_products__list"
            android:theme="@style/AppTheme.NoActionBar"></activity>
        <activity
            android:name=".Categories"
            android:label="@string/title_activity_categories"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".SignIn"
            android:label="@string/title_activity_sign_in"
            android:theme="@style/AppTheme.NoActionBar" />

        <service android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firbase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/bisc" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
    </application   >

</manifest>

这里还有 MyFirebaseMessagingService 代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Log.d("Noti: ", "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                Toast.makeText(this,"message", Toast.LENGTH_LONG).show();
            } else {
                // Handle message within 10 seconds

                Toast.makeText(this,"No message", Toast.LENGTH_LONG).show();//handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.d("Token",s);
    }
} 

标签: androidfirebase

解决方案


在 FCM 中有两种消息:通知和数据。但主要区别在于通知显示在通知托盘中,而数据则不显示。您必须发送数据通知并显示通知管理器收到的消息。此代码可以帮助您:

 @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {

    //        String title = remoteMessage.getNotification().getTitle();
    //        String message = remoteMessage.getNotification().getBody();



            createNotification(remoteMessage);


            }



        private void createNotification(RemoteMessage messageBody) {


            PushModel pushModel=new PushModel() ;

    //        pushModel = new Gson().fromJson(messageBody,PushModel.class);
           try {

               pushModel.setBody(messageBody.getData().get("body"));
               pushModel.setTitle(messageBody.getData().get("title"));
    //           pushModel = convertJsonToBaseApiModel(messageBody);
           }catch (Exception e){
               String s = e.getMessage();
           }


            Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            AppController.getPreferenceModel().setNotifMessage(pushModel.getBody());
            Intent intent1 = new Intent(this, SplashActivity.class);
            PendingIntent resultIntents = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_ONE_SHOT);

            String channelId = "Dialog";

            Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_ansar_logo)
                    .setContentTitle(pushModel.getTitle())
                    .setContentText(pushModel.getBody())
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setAutoCancel(true)

    //                .addAction(R.drawable.filter_outline, "Hello", resultIntents)
    //                .addAction(R.drawable.ic_alert, "Call", resultIntent)
                    .setSound(notificationSoundURI)
                    .setPriority(Notification.PRIORITY_MAX)
                    .setWhen(0)
                    .setContentIntent(resultIntent);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            // Since android Oreo notification channel is needed.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId,
                        "Channel human readable title",
                        NotificationManager.IMPORTANCE_DEFAULT);
                notificationManager.createNotificationChannel(channel);
            }

            notificationManager.notify(0, mNotificationBuilder.build());

        }





        public static PushModel convertJsonToBaseApiModel(String json) {


            String testTitle=json.substring(json.indexOf("title="),json.indexOf(","));

            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setLenient()
                    .create();
            Type listType = new TypeToken<PushModel>() {
            }.getType();
           PushModel pushModel = gson.fromJson(json, listType);
            return pushModel;
        }

推荐阅读