【问题标题】:Android Studio Firebase Cloud Messaging Not Working?Android Studio Firebase 云消息不工作?
【发布时间】:2021-11-21 21:46:17
【问题描述】:

我正在开发一个电子商务应用程序,当用户下订单时,卖家应该会收到新订单的通知。我可以发送通知,因为它显示“响应”的 toast 消息,但卖方未收到任何通知。我多次检查代码,但我仍然无法找出我在哪里犯了错误。这是我的代码

public class MyFirebaseMessaging extends FirebaseMessagingService {

    private static final String NOTIFICATION_CHANNEL_ID = "MY_NOTIFICATION_CHANNEL_ID";
    FirebaseAuth firebaseAuth;
    FirebaseUser firebaseUser;

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        String notificationType = remoteMessage.getData().get("notificationType");

        if (notificationType.equals("NewOrder")){
            String buyerUid = remoteMessage.getData().get("buyerUid");
            String sellerUid = remoteMessage.getData().get("sellerUid");
            String orderId = remoteMessage.getData().get("orderId");
            String notificationTitle = remoteMessage.getData().get("notificationTitle");
            String notificationMessage = remoteMessage.getData().get("notificationMessage");

            if (firebaseUser != null && firebaseAuth.getUid().equals(sellerUid)){
                showNotification(orderId,sellerUid,buyerUid,notificationTitle,notificationMessage,notificationType);
            }

        }

        if (notificationType.equals("OrderStatusChanged")){
            String buyerUid = remoteMessage.getData().get("buyerUid");
            String sellerUid = remoteMessage.getData().get("sellerUid");
            String orderId = remoteMessage.getData().get("orderId");
            String notificationTitle = remoteMessage.getData().get("notificationTitle");
            String notificationMessage = remoteMessage.getData().get("notificationMessage");

            if (firebaseUser != null && firebaseAuth.getUid().equals(buyerUid)){
                showNotification(orderId,sellerUid,buyerUid,notificationTitle,notificationMessage,notificationType);

            }
        }
    }

    private void showNotification(String orderId,String sellerUid,String buyerUid,String notificationTitle,String notificationDescription,String notificationType){
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        int notificationID = new Random().nextInt(3000);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            setUpNotificationChannel(notificationManager);
        }
        Intent intent = null;
        if (notificationType.equals("NewOrder")){
            intent = new Intent(this,ShopOrderDetails.class);
            intent.putExtra("orderId",orderId);
            intent.putExtra("orderBy",buyerUid);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else if (notificationType.equals("OrderStatusChanged")){
            intent = new Intent(this,UserOrderDetailsActivity.class);
            intent.putExtra("orderId",orderId);
            intent.putExtra("orderTo",sellerUid);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.indianflag);

        //notification sound
        Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
        notificationBuilder.setSmallIcon(R.drawable.indianflag)
        .setLargeIcon(largeIcon)
        .setContentTitle(notificationTitle)
        .setContentText(notificationDescription)
        .setSound(notificationSoundUri)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent);

        //show notification
        notificationManager.notify(notificationID,notificationBuilder.build());

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setUpNotificationChannel(NotificationManager notificationManager) {
        CharSequence channelName = "Some sample text";
        String channelDescription = "Channel Description Here";
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,channelName,NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setDescription(channelDescription);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        if (notificationManager != null){
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
}
private void prepareNotification(String orderId){
        String NOTIFICATION_TOPIC = "/topics/"+ Constants.FCM_TOPIC;
        String NOTIFICATION_TITLE = "New Order "+orderId;
        String NOTIFICATION_MESSAGE = "You have a new order";
        String NOTIFICATION_TYPE = "NewOrder";

        JSONObject notificationJo = new JSONObject();
        JSONObject notificationBodyJo = new JSONObject();

        Log.d("userId",mAuth.getUid());
        Log.d("shopId",shopId);
        Log.d("orderId",orderId);

        try{
            notificationBodyJo.put("notificationType",NOTIFICATION_TYPE);
            notificationBodyJo.put("buyerUid",mAuth.getUid());
            notificationBodyJo.put("sellerUid",shopId);
            notificationBodyJo.put("orderId",orderId);
            notificationBodyJo.put("notificationTitle",NOTIFICATION_TITLE);
            notificationBodyJo.put("notificationMessage",NOTIFICATION_MESSAGE);

            notificationJo.put("to",NOTIFICATION_TOPIC);
            notificationJo.put("data",notificationBodyJo);

        }catch (Exception e){
            Toast.makeText(ProceedToCheckoutActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        sendFCMNotification(notificationJo,orderId);
    }

    private void sendFCMNotification(JSONObject notificationJo, String timeStamp1) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notificationJo, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Toast.makeText(ProceedToCheckoutActivity.this, "Response", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ProceedToCheckoutActivity.this,UserOrderDetailsActivity.class);
                intent.putExtra("shopID",shopId);
                intent.putExtra("orderId",timeStamp1);
                startActivity(intent);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Error Here",error.toString());
                Toast.makeText(ProceedToCheckoutActivity.this, "Error", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ProceedToCheckoutActivity.this,UserOrderDetailsActivity.class);
                intent.putExtra("shopID",shopId);
                intent.putExtra("orderId",timeStamp1);
                startActivity(intent);
            }
        }){


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> headers = new HashMap<>();
                headers.put("Content-Type","application/json");
                headers.put("Authorization","key="+Constants.FCM_KEY);
                return headers;
            }
        };

        Volley.newRequestQueue(this).add(jsonObjectRequest);


    }

【问题讨论】:

    标签: firebase android-studio push-notification notifications firebase-cloud-messaging


    【解决方案1】:

    请使用改造或凌空向第二个用户发送通知。

    链接:sending fcm push notifications using retrofit library in android

    模块:应用程序依赖项

    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
    

    ApiClient

    public class ApiClient {
    
        private static final String BASE_URL = "https://fcm.googleapis.com/";
        private static Retrofit retrofit = null;
    
        public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }
    

    API接口

    public interface ApiInterface {
    
        @Headers({"Authorization: key=" + ConstantKey.SERVER_KEY, "Content-Type:application/json"})
        @POST("fcm/send")
        Call<ResponseBody> sendNotification(@Body RootModel root);
    }
    

    根模型

    public class RootModel {
    
        @SerializedName("to") //  "to" changed to token
        private String token;
    
        @SerializedName("notification")
        private NotificationModel notification;
    
        @SerializedName("data")
        private DataModel data;
    
        public RootModel(String token, NotificationModel notification, DataModel data) {
            this.token = token;
            this.notification = notification;
            this.data = data;
        }
    
        public String getToken() {
            return token;
        }
    
        public void setToken(String token) {
            this.token = token;
        }
    
        public NotificationModel getNotification() {
            return notification;
        }
    
        public void setNotification(NotificationModel notification) {
            this.notification = notification;
        }
    
        public DataModel getData() {
            return data;
        }
    
        public void setData(DataModel data) {
            this.data = data;
        }
    }
    

    通知模型

    public class NotificationModel {
    
        private String title;
        private String body;
    
        public NotificationModel(String title, String body) {
            this.title = title;
            this.body = body;
        }
    
        public String getBody() {
            return body;
        }
    
        public void setBody(String body) {
            this.body = body;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
    }
    

    数据模型

    public class DataModel {
    
        private String name;
        private String age;
    
        public DataModel(String name, String age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
    }
    

    使用此方法发送通知

    private void sendNotificationToUser(String token) {
        RootModel rootModel = new RootModel(token, new NotificationModel("Title", "Body"), new DataModel("Name", "30"));
    
        ApiInterface apiService =  ApiClient.getClient().create(ApiInterface.class);
        retrofit2.Call<ResponseBody> responseBodyCall = apiService.sendNotification(rootModel);
    
        responseBodyCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                Log.d(TAG,"Successfully notification send by using retrofit.");
            }
    
            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
    
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      相关资源
      最近更新 更多