java - 从我的应用程序收到消息时如何发送推送通知
问题描述
当用户收到我希望它播放声音的消息时,我正在使用 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);
它在应用程序打开时有效,但仅在模拟器测试设备上有效
解决方案
推荐阅读
- css - 如何将动画添加到材质 ui 卡
- ios - 删除最初不活动的队列
- r - How to get the n most common items in each group
- c# - Error when inject service into startup constructor
- php - 创建一个 for 循环以遍历大量 URL
- react-native - 在 Native Base (React Native) 中的 Accordion 内容中的 JSX
- javascript - 无法读取未定义的属性“地图” - 无法从 axios 请求映射数据
- wso2 - 如何访问和处理发送到 Ballerina 服务资源的 json 数组
- database - Flutter 应用程序是否可以使用 RethinkDB?
- node.js - MongoDB Atlas 连接不断下降