FCM не сделает уведомление - PullRequest
       27

FCM не сделает уведомление

0 голосов
/ 04 ноября 2019

У меня есть приложение чата, и я пытаюсь отобразить уведомление пользователю, как только получено новое сообщение.

Как только я запускаю упражнение, я вызываю 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();
                    }
                }
            });
}

И еще одна вещь - это моя задача:

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;
    }
}

Теперь проблема в том, что я не получаю никаких уведомлений.

Я вставил журналы, чтобы проверить, выполняется ли там код, и, кажется, он проходит все необходимые функции, но все равно не показываетчто угодно.

Я добавил приоритет = высокий, потому что я прочитал, что это может повлиять, но это не помогло.

Мой класс сообщений:

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 или что-то еще для негоработать или у меня есть другая ошибка, которую я не могу понять?

Спасибо

...