关于消息的Firebase推送通知收到错误

时间:2018-09-17 06:51:33

标签: android firebase push-notification

我正在尝试使用fcm发送推送通知。我还按照教程中给出的步骤添加了google-services.json文件。我可以在日志中看到类似这样的消息,但不能看到推送通知。

D/FA: Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=HomeScreenActivityTeacher, firebase_screen_id(_si)=2539281733171888617, message_device_time(_ndt)=0, message_name(_nmn)=bvvbv, message_time(_nmt)=1537166124, message_id(_nmid)=4182752688187919772}]
V/FA: Connection attempt already in progress
D/FA: Connected to remote service

Firebase控制台显示已传递消息,但在移动设备或模拟器上看不到该通知。请帮助我

这是我的服务课程

public class MyFirebaseMessagingService extends FirebaseMessagingService {


private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

private NotificationUtils notificationUtils;
Boolean isLoggedin;
SharedPreferences preferences;
Handler mHandler;
Intent i;
int indexOfCallerNumber;
String caller_Name;



@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    try {
        Log.e(TAG, "From: " + remoteMessage);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

if(remoteMessage.getNotification().getBody()!=null) {
       // Log.e(TAG, "Message Body: " + remoteMessage.getNotification().getBody());
    //}
    //showNotificationMessage(remoteMessage.getNotification().getBody());
//        String click_action=remoteMessage.getNotification().getClickAction();
   // Intent i=new Intent(click_action);
 ////////////////////////////////////////
        if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());

        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());

            Handler mHandler;
            //mHandler = new Handler() {
                handleDataMessage(json);
            //};
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(pushNotification);

        // play notification sound
        NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
        //Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.);
        //Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        //r.play();
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

    private void handleDataMessage (JSONObject json){

        Log.e(TAG, "push json: " + json.toString());

        try {
            //JSONObject data = json.getJSONObject("senderinfo");
          JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");

            //String imageUrl = data.getString("image");
            //String timestamp = data.getString("timestamp");
            //Common.caller_phoneNo=data.getString("caller_phone");
            /*  Log.d("Caller No",Common.caller_phoneNo);

           JSONObject payload = data.getJSONObject("payload");
            Common.SESSION_ID = payload.getString("session_id");
            Common.API_KEY = payload.getString("api_key");
            Common.TOKEN = payload.getString("token_id");


             /*OpenTokConfig.SESSION_ID = data.getString("session_id");
            OpenTokConfig.API_KEY = data.getString("api_key");
            OpenTokConfig.TOKEN = data.getString("token_id");*/

           /* Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);

            //Log.e(TAG, "payload: " + payload.toString());
            //Log.e(TAG, "imageUrl: " + imageUrl);
            //Log.e(TAG, "timestamp: " + timestamp);
            if(isUserLoggedIn()) {
                i = new Intent(Config.CLICK_ACTION);
            }
            else
            {
                i = new Intent(Config.CLICK_ACTION_LOGIN);*/
                //Common.LOGIN_CALLRECD=true;
            //}
          //  caller_Name=getCallerName();


            showNotificationMessage(getApplicationContext(), title, "incoming message",i);


            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
                //Common.call_recvd = true;
                //saveCallStatus();
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), RegistrationActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
           /* if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }*/
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }


/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message,Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message,intent);
   intent.setAction(Config.CLICK_ACTION);
    sendBroadcast(intent);


    startActivity(intent);
    //sendBroadcast(intent);

}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message,intent, imageUrl);
}

}

NotificationUtils.java

公共类NotificationUtils {

private static String TAG = NotificationUtils.class.getSimpleName();

private Context mContext;

BroadcastReceiver broadcastReceiver;

public NotificationUtils(Context mContext) {
    this.mContext = mContext;
}

public void showNotificationMessage(String title, String message, Intent intent) {
    showNotificationMessage(title, message,intent, null);
}

public void showNotificationMessage(final String title, final String message, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");

    if (!TextUtils.isEmpty(imageUrl)) {

        if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

            Bitmap bitmap = getBitmapFromURL(imageUrl);

            if (bitmap != null) {
                showBigNotification(bitmap, mBuilder, icon, title, message, resultPendingIntent, alarmSound);
            } else {
                showSmallNotification(mBuilder, icon, title, message, resultPendingIntent, alarmSound);
            }
        }
    } else {
        showSmallNotification(mBuilder, icon, title, message, resultPendingIntent, alarmSound);
        playNotificationSound();
    }
}


private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, PendingIntent resultPendingIntent, Uri alarmSound) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    inboxStyle.addLine(message);

    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
           // .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID, notification);
}

private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, PendingIntent resultPendingIntent, Uri alarmSound) {
    NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
    bigPictureStyle.setBigContentTitle(title);
    bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
    bigPictureStyle.bigPicture(bitmap);
    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(bigPictureStyle)
            //.setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
}

/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

// Playing notification sound
public void playNotificationSound() {
    try {
        Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");
        Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Method checks if the app is in background or not
 */
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

// Clears notification tray messages
public static void clearNotifications(Context context) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

public static long getTimeMilliSec(String timeStamp) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date date = format.parse(timeStamp);
        return date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0;
}
}

0 个答案:

没有答案
相关问题