我有一个聊天应用程序,我试图在收到新消息后向用户显示通知。
启动活动后,我将按以下方式调用onStart
:
@Override
protected void onStart() {
super.onStart();
popNotification();
}
popNotification
是为了检查我的数据库中是否有任何更新而调用的类。如果是,我调用另一个名为AddNotification()
public void popNotification() {
db.collection("Users").document(auth.getUid()).collection("MyChats")
.addsnapshotListener(new EventListener<Querysnapshot>() {
@Override
public void onEvent(@Nullable Querysnapshot value,@Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w("","Listen failed.",e);
return;
}
for (QueryDocumentsnapshot doc : value) {
if (doc.getId() != null) {
DocumentReference docRef = db.collection("Users").document(auth.getUid()).collection("MyChats").document(doc.getId());
docRef.get().addOnCompleteListener(new OnCompleteListener<Documentsnapshot>() {
@Override
public void onComplete(@NonNull Task<Documentsnapshot> task) {
if (task.isSuccessful()) {
Documentsnapshot document = task.getResult();
if (document.exists()) {
if(document.getLong("LastMessageTime") > document.getLong("lastChatVisited")){
AddNotification();
}
} else {
Log.d("","No such document");
}
} else {
Log.d("","get failed with ",task.getException());
}
}
});
}
}
}
});
}
和AddNotification()
:
private void AddNotification(){
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("","getInstanceId failed",task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
try {
String title = "TEST ";
MyTaskParams params = new MyTaskParams(token,title,"TTT!");
MyTask myTask = new MyTask();
myTask.execute(params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
最后一件事是mytask:
private class MyTask extends AsyncTask<MyTaskParams,Void,Void> {
@Override
protected Void doInBackground(MyTaskParams... params) {
String userDeviceIdKey = params[0].url;
String title = params[0].title;
String body = params[0].body;
String authKey = "XXX"; // You FCM AUTH key
String FMCurl = "https://fcm.googleapis.com/fcm/send";
URL url;
try {
url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey);
json.put("priority","high");
JSONObject info = new JSONObject();
info.put("title",title); // Notification title
info.put("body",body); // Notification body
json.put("data",info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
现在,问题在于我没有收到任何通知。
我插入Logs是为了检查代码是否在此处运行,并且似乎通过了所有必需的功能,但是仍然没有显示任何内容。
我添加了优先级=高,因为我读了它可能会影响,但没有帮助。
我的消息类别是:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
@Override
public void onmessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG,"From: " + remoteMessage.getFrom());
Log.d(TAG,"Notification Message Body: " + remoteMessage.getData().get("body"));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"29358305")
.setSmallIcon(R.drawable.ic_launcher_custom_background)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("body"))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(remoteMessage.getData().get("body")))
.setLargeIcon(BitmapFactory.decodeResource(getapplicationContext().getResources(),R.mipmap.ic_launcher))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//createNotificationChannel();
NotificationmanagerCompat notificationmanager = NotificationmanagerCompat.from(this);
notificationmanager.notify(235345305,builder.build());
}
}
编辑:
在创建通知时,我也尝试使用以下内容而没有任何改进:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
@Override
public void onmessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG,"From: " + remoteMessage.getFrom());
Log.d(TAG,"Notification Message Body: " + remoteMessage.getData().get("body"));
createNotificationChannel();
notifyThis(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
}
private void createNotificationChannel() {
// Create the NotificationChannel,but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ABC";
String description = "ABCDE";
int importance = Notificationmanager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("191919",name,importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
Notificationmanager notificationmanager = getSystemService(Notificationmanager.class);
notificationmanager.createNotificationChannel(channel);
}
}
public void notifyThis(String title,String message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,"191919")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationmanagerCompat notificationmanager = NotificationmanagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationmanager.notify(0,mBuilder.build());
}
我是否还需要添加onPause
或其他内容才能使其正常工作,或者我还有其他一些我无法理解的错误?
谢谢