首页 > 解决方案 > 从我的应用程序收到消息时如何发送推送通知

问题描述

当用户收到我希望它播放声音的消息时,我正在使用 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);

它在应用程序打开时有效,但仅在模拟器测试设备上有效

标签: javaandroidpush-notification

解决方案


推荐阅读