从我的应用收到消息后如何发送推送通知

时间:2019-07-06 09:09:36

标签: java android push-notification

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

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

0 个答案:

没有答案
相关问题