繁体   English   中英

当应用程序处于后台和终止状态时如何移动不同活动的通知导航

[英]How to move notification navigation for different activity when app is background and killed state

  private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    //Displaying data in log
    //It is optional

    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

    Log.e("ggjhgjh", String.valueOf(remoteMessage.getData()));

    String title = String.valueOf(remoteMessage.getNotification().getTitle());
    String Subtitle = String.valueOf(remoteMessage.getNotification().getBody());

    if (remoteMessage.getData() != null) {
        JSONObject jsonObjectItem = null;
        Log.d(TAG, "Notification Data: " + remoteMessage.getData());
        jsonObjectItem = new JSONObject(remoteMessage.getData());
        handleDataMessage(jsonObjectItem, title, Subtitle);
    } else {
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getNotification().getBody());

            JSONObject jsonObjectItem = null;
            jsonObjectItem = new JSONObject(remoteMessage.getData());
            handleDataMessage(jsonObjectItem, title, Subtitle);

        }
    }

    //Calling method to generate notification
    //sendNotification(remoteMessage.getNotification().getBody());
}

public void handleDataMessage(JSONObject json, String title, String subTitle) {
    Intent intent = null;
    Bundle bundle;
    String requestId, packetType, packetDetails, totalpacket, donarImage, pTime, pAddress;

    try {
        if (title.equals("New Coupons in store")) {
            String couponName = json.getString("name");
            String couponId = json.getString("coupon_id");
            String categoryId = json.getString("category_id");
            String couponPoint = json.getString("coupon_point");
            String couponImage = json.getString("image");
            String couponStatus = json.getString("status");
            String noOfcoupon = json.getString("no_of_coupon");
            String usedcoupon = json.getString("used_coupon");
            String storeId = json.getString("store_id");
            String merchant_id = json.getString("merchant_id");
            String description = json.getString("description");
            String couponstartDate = json.getString("start_date");
            String couponEndDate = json.getString("end_date");
            CouponModel couponModel = new CouponModel(couponName, couponId, categoryId, couponPoint, couponImage, couponStatus, noOfcoupon, usedcoupon, storeId, merchant_id, description, couponstartDate, couponEndDate);
            intent = new Intent(MyFirebaseMessagingService.this, Activity_CouponDetails.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            bundle = new Bundle();
            bundle.putSerializable("couponModel", couponModel);
            intent.putExtras(bundle);
        } else if (title.equals("Your Request is Accepted")) {
            requestId = json.getString("id");
            packetType = json.getString("packet_type");
            packetDetails = json.getString("packet_detail");
            totalpacket = json.getString("total_packets");
            donarImage = json.getString("donar_image");
            pTime = json.getString("food_cook_time");
            pAddress = json.getString("address");

            intent = new Intent(MyFirebaseMessagingService.this, Activity_RequestDetails.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            bundle = new Bundle();
            intent.putExtra("pickupId", requestId);
            intent.putExtra("packetType", packetType);
            intent.putExtra("packetDetail", packetDetails);
            intent.putExtra("totalPackets", totalpacket);
            intent.putExtra("donar_image", donarImage);
            intent.putExtra("time", pTime);
            intent.putExtra("address", pAddress);
            intent.putExtras(bundle);

        }
 PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseMessagingService.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            //PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
            Notification myNotification = new NotificationCompat.Builder(MyFirebaseMessagingService.this)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setSmallIcon(R.mipmap.launcher)
                    .setContentTitle(title)
                    .setContentText(subTitle)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setColor(0xff493C7C)
                    .setLights(0xff493C7C, 1000, 1000)
                    .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .build();

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, myNotification);

    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
        }
}
}

从您的服务器请求中完全删除通知负载。 仅发送数据并在 onMessageReceived() 中处理它,否则当应用程序处于后台或被杀死时,您的 onMessageReceived 将不会被触发。

我有同样的问题。 使用“数据消息”代替“通知”更容易。 数据消息总是加载 onMessageReceived 类。

在该课程中,您可以使用 onMessageReceived 中的通知构建器制作您自己的通知。

 @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
        }

        private void sendNotification(String messageTitle,String messageBody) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);

            long[] pattern = {500,500,500,500,500};

            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setContentTitle(messageTitle)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setVibrate(pattern)
                    .setLights(Color.BLUE,1,1)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
        }

尝试如下

在您的通知服务类中这样写,并确保在您的清单文件中定义了服务

    private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "push json: " + json.toString());

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

          String title = data.getString("title");
          String message = data.getString("body");

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



        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(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);
            resultIntent.putExtra("frag","Notification");

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


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

这是 Notification util 类,用于检查应用程序是否为后台以及通知修改的其他内容。

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

    private Context mContext;
    NotificationCompat.InboxStyle inboxStyle;
    private static int value = 0;
    private final int NOTIFICATION_ID = 237;

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

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

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


        // notification icon
        final int icon = R.drawable.ic_status_notification;

        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);
        Resources res = mContext.getResources();
         inboxStyle = new NotificationCompat.InboxStyle();
        Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.profile);
               mBuilder.setLargeIcon(bitmap);

        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()) {
//


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


    private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, 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.drawable.ic_status_notification)
                .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, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

        inboxStyle.setBigContentTitle("Matrix Messages");
        inboxStyle.addLine("You have "+value+" new  notification");
        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(inboxStyle)
                .setWhen(getTimeMilliSec(timeStamp))
                .setSmallIcon(R.drawable.ic_status_notification)
                .setLargeIcon(bitmap)
                .setContentText(message)
                .build();

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify("Matrix",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 {
            try {

                List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                ComponentName componentInfo = taskInfo.get(0).topActivity;
                if (componentInfo.getPackageName().equals(context.getPackageName())) {
                    isInBackground = false;
                }
            }catch (SecurityException e)
            {
                e.printStackTrace();
            }
        }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM