Firebase通知发送Android脚本(Java)返回无效注册

时间:2019-07-16 07:28:14

标签: android firebase

我一直尝试从logcat中从android设备发送通知时遇到错误,但尝试却无济于事

{"multicast_id":5162718122421221171,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

这是我用于发送消息的android代码,我正在主题部分中发送userABC主题。

public void SendNotification(String Title, String Message){
    NOTIFICATION_TITLE = Title;
    NOTIFICATION_MESSAGE = Message;

    JSONObject notification = new JSONObject();
    JSONObject notifcationBody = new JSONObject();
    try {
        notifcationBody.put("title", NOTIFICATION_TITLE);
        notifcationBody.put("message", NOTIFICATION_MESSAGE);

        notification.put("to", TOPIC);
        notification.put("data", notifcationBody);
    } catch (JSONException e) {
        Log.e(TAG, "onCreate: " + e.getMessage() );
    }
    sendNotification(notification);
}

private void sendNotification(JSONObject notification) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,

    new com.android.volley.Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG, "onResponse: " + response.toString());

                }
            },
            new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), "Request error", Toast.LENGTH_LONG).show();
                    Log.i(TAG, "onErrorResponse: Didn't work");
                }
            }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("Authorization", serverKey);
            params.put("Content-Type", contentType);
            return params;
        }
    };
    MySingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}

这是我的FirebaseInstanceIDService.java类

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "mFirebaseIIDService";
private static final String SUBSCRIBE_TO = "userABC";

@Override
public void onTokenRefresh() {
    /*
      This method is invoked whenever the token refreshes
      OPTIONAL: If you want to send messages to this application instance
      or manage this apps subscriptions on the server side,
      you can send this token to your server.
    */
    String token = FirebaseInstanceId.getInstance().getToken();

    // Once the token is generated, subscribe to topic with the userId
    FirebaseMessaging.getInstance().subscribeToTopic(SUBSCRIBE_TO);
    Log.i(TAG, "onTokenRefresh completed with token: " + token);
    sendRegistrationToServer(token);
}

private void sendRegistrationToServer(String token) {
    // send token to web service ??
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("server/saving-data/IDs");
    // then store your token ID
    ref.push().setValue(token);
}

}

这是我的FirebaseMessagingService.java类

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

private final String ADMIN_CHANNEL_ID ="admin_channel";

@Override
public void onNewToken(String token) {
    Log.d("TAG", "Refreshed token: " + token);
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d("THIS", "Refreshed token: " + refreshedToken);
    FirebaseMessaging.getInstance().subscribeToTopic("userABC");
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token) {
    // send token to web service ??
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("server/saving-data/IDs");
    // then store your token ID
    ref.push().setValue(token);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    final Intent intent = new Intent(this, MainActivity.class);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationID = new Random().nextInt(3000);

  /*
    Apps targeting SDK 26 or above (Android O) must implement notification channels and add its notifications
    to at least one of them. Therefore, confirm if version is Oreo or higher, then setup notification channel
  */
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        setupChannels(notificationManager);
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this , 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher);

    Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(largeIcon)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("message"))
            .setAutoCancel(true)
            .setSound(notificationSoundUri)
            .setContentIntent(pendingIntent);

    //Set notification color to match your app color template
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        notificationBuilder.setColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    notificationManager.notify(notificationID, notificationBuilder.build());
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(NotificationManager notificationManager){
    CharSequence adminChannelName = "New notification";
    String adminChannelDescription = "Device to devie notification";

    NotificationChannel adminChannel;
    adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
    adminChannel.setDescription(adminChannelDescription);
    adminChannel.enableLights(true);
    adminChannel.setLightColor(Color.RED);
    adminChannel.enableVibration(true);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(adminChannel);
    }
}

}

1 个答案:

答案 0 :(得分:0)

FirebaseInstanceIdService现在已弃用

因此您可以按以下方式更改注册逻辑

FcmRegistrationManager.java

public class FcmRegistrationManager {

private static final String TAG = "FcmRegistrationManager"

/*This is async call*/
public void registerWithFcm(){
    FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

                Log.d(TAG, msg);
                sendRegistrationToServer(token)

            }
        });

}

private void sendRegistrationToServer(String token) {
    // send token to web service ??
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("server/saving-data/IDs");
    // then store your token ID
    ref.push().setValue(token);
}

}

sendNotification()和FirebaseMessagingService类未更改。 更多参考:https://firebase.google.com/docs/cloud-messaging/android/client

让我仍然无法正常工作,我将与您分享有效的代码。