我已经构建了一个聊天应用程序。它工作正常。两个用户都可以轻松聊天 但是我得到Stuck的是,如果一个用户的应用程序处于后台并且屏幕关闭,则无法通知用户该收到的消息。
我现在想要的是在我的应用程序中,当userA向userB发送消息,而userB mobile空闲但应用程序在后台运行时,userB可以获得有关该消息的通知。和userB可以打开聊天活动并阅读消息。
我的firebase通知正在使用firebase控制台,但我不知道如何调用实例ID并将其从api发送到特定设备,特定用户获取有关收到的消息的通知,当应用程序屏幕关闭且应用程序是在背景状态下运行。我应该如何实现它?
我的firebase实例ID服务类在这里:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
}
}
以下是我的MyFirebase Messaging Service Class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification().getBody() != null) {
Log.e("FIREBASE", "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
RemoteMessage.Notification notification = remoteMessage.getNotification();
Intent intent = new Intent(this, LoggedInView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.first_aid))
.setSmallIcon(R.drawable.first_aid)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
这是我的聊天活动:
public class Chat extends AppCompatActivity {
LinearLayout layout;
ImageView sendButton,vidcall;
EditText messageArea;
ScrollView scrollView;
Firebase reference1, reference2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_chat);
layout = (LinearLayout)findViewById(R.id.layout1);
sendButton = (ImageView)findViewById(R.id.sendButton);
vidcall = (ImageView)findViewById(R.id.vidBtnk);
messageArea = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
Firebase.setAndroidContext(this);
reference1 = new Firebase("https://*******.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
reference2 = new Firebase("https://*******.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
if(!messageText.equals("")){
Map<String, String> map = new HashMap<String, String>();
map.put("message", messageText);
map.put("user", UserDetails.username);
reference1.push().setValue(map);
reference2.push().setValue(map);
}
messageArea.setText("");
}
});
vidcall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Chat.this, ConnectActivity.class));
}
});
reference1.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("user").toString();
if(userName.equals(UserDetails.username)){
addMessageBox("You:-\n" + message, 1);
}
else{
addMessageBox(UserDetails.chatWith + ":-\n" + message, 2);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
// boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(Chat.this);
builder1.setMessage("CAUTION! -> Do Wish to End this Session");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
dialog.cancel();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
public void addMessageBox(String message, int type){
TextView textView = new TextView(Chat.this);
textView.setText(message);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, 10);
textView.setLayoutParams(lp);
if(type == 1) {
textView.setBackgroundResource(R.drawable.rounded_corner1);
}
else{
textView.setBackgroundResource(R.drawable.rounded_corner2);
}
layout.addView(textView);
scrollView.fullScroll(View.FOCUS_DOWN);
}
}
答案 0 :(得分:14)
您需要在后台运行的服务才能捕获PUSH通知并将其显示给用户,以及Firebase通知服务为您提供的功能。我有这个(你必须修改它以便在出现通知时做你想做的事):
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification().getBody() != null) {
Log.e("FIREBASE", "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
RemoteMessage.Notification notification = remoteMessage.getNotification();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.logo_gris))
.setSmallIcon(R.drawable.logo_gris)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
答案 1 :(得分:0)
我解决了这个问题可能对某人有帮助,
为了通过api向单个设备发送firebase的通知如下:
1:生成实例ID,每个设备都是唯一的
print(sess.run(y[tf.argmax(y, 1)], feed_dict={x: f1}))
注意:您可以从应用程序中的任何位置调用Instance Id,如下所示:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
}
}
此令牌必须用于向单个设备发送通知,它是您可以将其存储在firebase数据库中的设备的ID
String tkn = FirebaseInstanceId.getInstance().getToken();
Toast.makeText(Doc_users.this, "Current token ["+tkn+"]",
Toast.LENGTH_LONG).show();
Log.d("App", "Token ["+tkn+"]");
2:现在您可以构建逻辑来获取这些ID并构建您的请求
reference.child(UserDetails.username).child("token").setValue(tokun);
通知将在您的设备发送的单个设备上生成,您可以调试以放置您自己的设备密钥并使用邮递员获得有效请求:祝您好运
答案 2 :(得分:0)
您好我使用firebase消息传递实现了聊天应用程序。
您可以执行以下步骤
1)实现sendRegistrationToServer(String token){ 进行异步调用以存储在后端服务器中生成的令牌(使用令牌生成的映射用户) }
2)在聊天活动中,sendmessage()应该向服务器发送消息给secondUser()
3)通过查看usertoken,我们应该将通知从后端服务器推送到firebase服务器。
4)实施onMessageReceived()以显示通知