Когда пользователь нажимает на уведомление, оно не запускает определенную активность, когда приложение находится на переднем плане. - PullRequest
0 голосов
/ 14 апреля 2019

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

Случаи

A, когда пользователь изначально запускает приложение, и приходит уведомление, затем пользователь нажимает на уведомление о том, что в данный момент открывается определенное действие. Когда я убиваю приложение и перезапускаю уведомление, приходят уведомления, затем нажимают на уведомление, затем открывают определенное открытое действие.но теперь мое приложение в уведомлении переднего плана / фона нажимает на уведомление о том, что время, когда определенное действие не открывается.

Мое действие является базовым действием, в котором я определил несколько условий, таких как

  • когда приходит уведомление о нас, затем перенаправить на фрагмент о нас
  • когда приходит уведомление об обмене сообщениями в чате, а затем перенаправить на фрагмент чата

Код

Notiifcationmessage service class TvamFirebaseMessagingService extends FirebaseMessagingService 
{

    private static final String TAG = "MyFirebaseMsgService";
    String CHANNEL_ID = "my_channel_01";// The id of the channel.
    private static PowerManager.WakeLock wakeLock;
    private Intent notificationIntent;
    private PendingIntent contentIntent;
    private String urlstring="";
    private String message;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e("push", "data: " + remoteMessage.getFrom().toString());

        if (remoteMessage.getData().size() > 0) {
            acquire(getApplicationContext());
            release();
            Map<String, String> data = remoteMessage.getData();
            String notificationMsg = "",messageType="";


            try {
                JSONObject jsonObject = new     JSONObject(data.get("message"));
                notificationMsg = jsonObject.get("message").toString();
//                sendNotification(notificationMsg, false,false);
                messageType=jsonObject.getJSONObject("type").getJSONObject("data").getString("msg_type");
                message=jsonObject.getJSONObject("type").getJSONObject("data").getString("message");
                urlstring=jsonObject.getJSONObject("type").getJSONObject("data").getString("url");

                if (data.containsKey("hc_type") && data.containsKey("chat_id")) {
                    sendNotification(notificationMsg, true, false,"");
                } else if (jsonObject.getJSONObject("type").has("type") && jsonObject.getJSONObject("type").getString("type").equalsIgnoreCase("BROADCAST")) {
                    sendNotification(notificationMsg, false, true,messageType);
                } else {
                    sendNotification(notificationMsg, false, false,"");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d("message", data.get("message"));
                notificationMsg = data.get("message").toString();
                if (data.containsKey("hc_type") && data.containsKey("chat_id")) {
                    sendNotification(notificationMsg, true, false,"");
                } else if (data.containsKey("type") && data.get("type").equalsIgnoreCase("BROADCAST")) {
                    sendNotification(notificationMsg, false, true,messageType);
                } else {
                    sendNotification(notificationMsg, false, false,"");
                }
            }
        }

    }

    @Override
    public void onNewToken(String token) {
        Preferences.setPreferences(PreferencesConstants.DEVICE_TOKEN, token);
    }


    public void sendNotification(String notificationMsg, boolean isFromHelpCranch, Boolean isBroadcatsMessage,String messageType) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Hello";// The user-visible name of the channel.
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            mNotificationManager.createNotificationChannel(mChannel);
        }
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder mBuilder;
        if (isFromHelpCranch) {
            notificationIntent = new Intent(getApplicationContext(), BaseActivity.class).putExtra("from", "notification");
            //    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.tvam_logo)
                        //   .setContentTitle("Tvam (त्वम्) - Vedic Astrology & You")
                        //  .setContentTitle("Tvam (त्वम्) - Vedic Astrology & You")

                        .setContentText("[Tvam (त्वम्)]: " + notificationMsg)
                        .setSound(uri)
                        .setPriority(Notification.PRIORITY_HIGH)
                        .setContentIntent(contentIntent)
                        .setChannelId(CHANNEL_ID);
    } else if (isBroadcatsMessage && !isFromHelpCranch) {
        notificationIntent = new Intent(getApplicationContext(), BaseActivity.class)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TASK).
        putExtra("from", "notification_3").
        putExtra("type", messageType).
        putExtra("url", urlstring).
        putExtra("content", message);
        contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.tvam_logo)
                        //  .setContentTitle("Tvam (त्वम्) - Vedic Astrology & You")
                        .setContentText("[Tvam (त्वम्)]: " + notificationMsg)
                        //  .setContentText(notificationMsg)
                        .setContentIntent(contentIntent)
                        .setSound(uri)
                        .setPriority(Notification.PRIORITY_HIGH)
                        .setChannelId(CHANNEL_ID);
    } else {
        notificationIntent = new Intent(getApplicationContext(), BaseActivity.class).putExtra("from", "notification_2");
     //   notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.tvam_logo)
                        //  .setContentTitle("Tvam (त्वम्) - Vedic Astrology & You")
                        .setContentText("[Tvam (त्वम्)]: " + notificationMsg)
                        //  .setContentText(notificationMsg)
                        .setContentIntent(contentIntent)
                        .setSound(uri)
                        .setPriority(Notification.PRIORITY_HIGH)
                        .setChannelId(CHANNEL_ID);
    }
    //    mNotificationManager.notify();
    mNotificationManager.notify(001, mBuilder.build());
}


@SuppressLint("InvalidWakeLockTag")
public static void acquire(Context context) {
    if (wakeLock != null)
        wakeLock.release();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "WakeLock");
    wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
}

public static void release() {
    if (wakeLock != null)
        wakeLock.release();
    wakeLock = null;
}
...