我创建了一个聊天应用程序,它能够正常运行。两个用户都可以轻松聊天。但是,如果其中一个用户的应用程序在后台且屏幕关闭,则该用户将无法收到接收到的消息通知。
现在我想要实现的是,在我的应用程序中,当用户A向用户B发送消息时,如果用户B的手机处于空闲状态但应用程序在后台运行,则用户B可以收到有关该消息的通知。用户B可以打开聊天界面并阅读该消息。
我的Firebase通知从Firebase控制台工作正常,但是我不知道如何调用实例ID并从API发送到特定设备,以便特定用户通知收到的消息,当应用程序屏幕关闭且应用程序处于后台状态时。我该如何实现它?
这是我的Firebase实例ID服务类:
现在我想要实现的是,在我的应用程序中,当用户A向用户B发送消息时,如果用户B的手机处于空闲状态但应用程序在后台运行,则用户B可以收到有关该消息的通知。用户B可以打开聊天界面并阅读该消息。
我的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消息服务类
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);
}
}