Как исправить сервис Firebase Instant ID - PullRequest
0 голосов
/ 27 марта 2019

Я пишу приложение и хочу внедрить в него push-уведомления, чтобы уведомлять своих пользователей о происходящем. Я осмотрелся и нашел нужный мне код, но не уверен, как решить эту проблему, с которой сталкиваюсь. Это может быть из-за того, что код устарел или неправильно начинать. Вот о чем я говорю:

public class FirebaseInstanceIDService extends FirebaseInstanceIdService implements Constants
public class FireBaseMessagingService extends FirebaseMessagingService implements Constants

Удаление навесного оборудования Константы приведут к его поломке и будут использованы в Манифесте, где мне нужно его вызвать.

Я пытался удалить агрегат, но он вызывает другую ошибку, которая не может быть публичной, если я удаляю публичную версию и просто оставляю "класс", он работает, но я не могу вызвать манифест приложения

ID службы

import android.util.Log;
import android.view.View;

import com.google.android.gms.common.internal.Constants;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

 public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService implements Constants {
    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
    }
}

Служба сообщений

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.common.internal.Constants;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

public class FireBaseMessagingService extends FirebaseMessagingService implements Constants {
    private static final String TAG = "MyFirebaseMsgService";
    private static int count = 0;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
        Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
        Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
//Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getTitle(),
                remoteMessage.getNotification().getBody(), remoteMessage.getData());
    }
    //This method is only generating push notification
    private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
        PendingIntent contentIntent = null;
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(contentIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(count, notificationBuilder.build());
        count++;
    }
}

Это полный код, который я пытаюсь использовать

Я ожидаю, что он сможет использовать его для push-уведомлений. Но если я получу ошибку, она не сможет быть использована.

1 Ответ

0 голосов
/ 27 марта 2019

Чтобы push-уведомления Firebase работали на Android, вот что вам нужно сделать в вашем Android-приложении,

  1. Добавьте зависимость firebase в свой файл gradle и поместите файл google-services.json, загруженный с консоли firebase, в свой проект.

    compile "com.google.firebase:firebase-messaging:17.3.4"
    
  2. Создание приемника для получения push-токена и полезных данных уведомления.

    public class FCMNotificationReceiver extends FirebaseMessagingService 
    {
      @Override
      public void onNewToken(String s) {
          super.onNewToken(s);
          // send token to your server.
    
      }
    
     @Override
      public void onMessageReceived(RemoteMessage remoteMessage) {
          super.onMessageReceived(remoteMessage);
          // use your own logic here to process notification. For example, 
          sendNotification(remoteMessage.getNotification().getTitle(),
              remoteMessage.getNotification().getBody(), remoteMessage.getData());
      }
    
    }
    
  3. Зарегистрируйте вышеуказанную услугу в манифесте


 <service android:name=".FCMNotificationReceiver">
             <intent-filter>
                 <action android:name="com.google.firebase.MESSAGING_EVENT"/>
             </intent-filter>
 </service>

  1. При желании вы также можете вызвать firebase, когда ваше приложение начнет получать push-токен.

    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    String mToken = instanceIdResult.getToken();
                    // send token to your server.

                }
            });

...