Push-уведомления не работают, когда приложение открыто?

#java #android #firebase #push-notification #firebase-cloud-messaging

#java #Android #firebase #push-уведомление #firebase-облако-обмен сообщениями

Вопрос:

Я пытаюсь использовать FCM, а уведомления работают только тогда, когда я не использую приложение.

когда я отправляю уведомление с устройства A на устройство B, тогда устройство B получает сообщение и «показывает всплывающее уведомление со звуком по умолчанию», и все в порядке … (это происходит, когда устройство B не использует приложение).

когда я отправляю уведомление с устройства A на устройство B, то устройство B получает сообщение методом onMessageReceived (), но «не показывает всплывающее уведомление со звуком по умолчанию».. (это происходит, когда устройство B использует приложение, я имею в виду, когда приложение открыто и используется).

это мой код FireIDService.java

 public class FireIDService extends FirebaseInstanceIdService {

    private final String TAG = "FireIDService";

    @Override
    public void onTokenRefresh() {
        String tkn = FirebaseInstanceId.getInstance().getToken();
        Log.d("Not","Token [" tkn "]");
        sendRegistrationToServer(tkn);
    }


    private void sendRegistrationToServer(String token) {
        saveDeviceToken(token);
    }

    private void saveDeviceToken(String deviceToken) {
        //some code..
                    if(response.body().getStatus() == 1){
                        doStuff();
                    }
        //some code...
            }

            @Override
            public void onFailure(Call<SaveDeviceTokenResponse> call, Throwable t) {
                //code...
            }
        });
    }

    private void doStuff(){
        Intent intent = new Intent(this, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("FCM Message")
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1410 /* ID of notification */, notificationBuilder.build());
    }
}
  

FireBaseMsgService.java

 public class FireBaseMsgService  extends FirebaseMessagingService{

    private final String TAG = "FireBaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);


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


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "test")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background))
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setColor(0xffff7700)
                .setVibrate(new long[]{100, 100, 100, 100})
                .setPriority(Notification.PRIORITY_MAX)
                .setSound(defaultSoundUri);

        Intent resultIntent = new Intent(this, SplashActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(SplashActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        notificationBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        mNotificationManager.notify(1, notificationBuilder.build());
    }

}

  

это то, что добавлено к AndroidManifest.xml файл

 <service android:name=".FireIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FireBaseMsgService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
  

и это класс Notify, который нужно выполнить

 public class Notify extends AsyncTask<Void,Void,Void>{

    private String tkn;
    private String title;
    private String body;

    public Notify(String tkn, String title, String body){
        this.tkn = tkn;
        this.title = title;
        this.body = body;
    }

    @Override
    protected Void doInBackground(Void... voids) {

        Log.e("Token: ", tkn);
        Log.e("Title: ", title);
        Log.e("Body: ", body);

        try {

            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key=KEY_HERE");
            conn.setRequestProperty("Content-Type", "application/json");

            JSONObject json = new JSONObject();

            json.put("to", tkn);


            JSONObject info = new JSONObject();
            info.put("title", title);   // Notification title
            info.put("body", body); // Notification body
            info.put("priority", "high");
            info.put("show_in_foreground", "true");

            json.put("notification", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            conn.getInputStream();

        }
        catch (Exception e)
        {
            Log.d("Error","" e);
        }


        return null;
    }

}
  

Ответ №1:

Если вы используете Android 8.0 . Вам нужно указать channelId для уведомления. Когда ваше приложение работает в фоновом режиме (как упоминалось в вашем первом случае), push-уведомление поступает в панель системных уведомлений, а не в FireBaseMsgService, и оно автоматически обрабатывается системой с помощью channelId, который создается самой системой. Когда ваше приложение находится на переднем плане (второй случай), выполняется FireBaseMsgService, и вам необходимо создать идентификатор канала уведомления

Комментарии:

1. ваш ответ кажется правильным, но не могли бы вы, пожалуйста, сказать, где и при каких условиях я должен добавить этот канал уведомлений, как может выглядеть код в моем случае! не могли бы вы, пожалуйста, помочь с этим?

2. Канал уведомлений используется в Android 8.0 более поздней версии. developer.android.com/training/notify-user /…

3. Спасибо Саурав Кумар, Ваш ответ был именно тем, что я ищу, теперь он работает идеально, сообщение пришло в обоих случаях.

4. Рад, что вам понравилось.