как отправить push-уведомление при получении сообщения из моего приложения - PullRequest
1 голос
/ 06 июля 2019

Я пишу простое приложение для сообщений, использующее FireBase, когда пользователь получает сообщение, которое я хочу, чтобы оно воспроизводило звук.и показать уведомление, если приложение закрыто.код, который я использовал, работает в эмуляторе, пока приложение открыто, но как только приложение закрыто или свернуто, оно ничего не делает.Кроме того, когда я пытаюсь использовать реальное устройство вместо эмулятора, оно ничего не делает.

Я думал, что это может быть связано с разрешениями, но я прочитал, что уведомления похожи на интернет-разрешение и не нужны.

private void Display_Messages() {
    ListView listOfMessages = findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessage>(this, 
ChatMessage.class,
            R.layout.message, 
    FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessage model, int 
   position) {
            // Get references to the views of message.xml
                TextView messageText = v.findViewById(R.id.message_text);
                TextView messageUser = v.findViewById(R.id.message_user);
                TextView messageTime = v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());

            // Format the date before showing it
            messageTime.setText(DateFormat.format("dd-MM-yyyy 
(HH:mm:ss)",
                    model.getMessageTime()));

            //Define Notification Manager
            NotificationManager notificationManager = 
(NotificationManager) 
getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);

//Define sound URI
            Uri soundUri = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder mBuilder = new 
NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("New Message from: " + 
USERNAME_STRING)
                    .setContentText(message)
                    .setSound(soundUri); //This sets the sound to play

//Display notification
            notificationManager.notify(0, mBuilder.build());
        }
    };
    listOfMessages.setAdapter(adapter);

работает при открытом приложении, но только на тестовом устройстве эмулятора

...