Попытка открыть фрагмент при нажатии push-уведомления.Не работает - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь открыть фрагмент с помощью push-уведомления, которое запускается в firebase. Это не работает. Вот MessageService.java

private void showNotification(String title, String body) {
        String NOTIFICATION_CHANNEL_ID = "plan.services.test";

        Intent openMain = new Intent(this, MainActivity.class);
        openMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        openMain.putExtra("checkNotification", "openOrder");
        Log.d(TAG, "order string in msg service:"+openMain.getStringExtra("checkNotification"));
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent orderIntent = PendingIntent.getActivity(OrderMsgService.this, 1, openMain, PendingIntent.FLAG_UPDATE_CURRENT);
        Log.d(TAG, "order intent:"+ orderIntent);

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
            currentapiVersion = R.drawable.icon_notification;
        } else{
            currentapiVersion = R.mipmap.image_main_logo;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder notificationChannelBuilder = new NotificationCompat.Builder(OrderMsgService.this, NOTIFICATION_CHANNEL_ID) // For Newer API
                    .setSmallIcon(currentapiVersion)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .setWhen(System.currentTimeMillis())
                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setContentIntent(orderIntent);

            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);

            channel.enableLights(true);
            channel.setLightColor(Color.GREEN);
            channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            channel.enableVibration(true);
            channel.setDescription("Plan Notifications");
            notificationManager.createNotificationChannel(channel);

            notificationManager.notify(1, notificationChannelBuilder.build());
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)//for older API

                    .setSmallIcon(currentapiVersion)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .setWhen(System.currentTimeMillis())
                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setContentIntent(orderIntent);

            notificationManager.notify(1, notificationBuilder.build());
        }
    }

А вот метод onCreate в MainActivity

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String orderFragment = getIntent().getStringExtra("openOrder");
        Log.d(TAG, "order string in main activity:"+orderFragment);
        // Launch order if triggered from notification; otherwise open mealplan
        if (orderFragment != null) {
            if (orderFragment.equals("openOrder")) {
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new OrderFragment(), null).commit();
            }
        } else {
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
        }
    }

Мне все равно, если я отправлю логическое, int или строку. Я просто хочу отправить какой-нибудь флаг, чтобы я мог открыть нужный фрагмент.

ОБНОВЛЕНИЕ Вот рабочий код. Я до сих пор не знаю, что я сделал или почему это работает. Но я больше не буду касаться этого и теперь буду просто копировать + вставлять это.

private void showNotification(String title, String body) {

        long notificationId = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Intent openMain = new Intent(this, MainActivity.class);
        openMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        openMain.putExtra("checkNotification", "openOrder");

        PendingIntent orderIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), openMain, PendingIntent.FLAG_UPDATE_CURRENT);
        Log.d(TAG, "order intent:"+ orderIntent);

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
            currentapiVersion = R.drawable.icon_notification;
        } else{
            currentapiVersion = R.mipmap.image_main_logo;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationCompat.Builder notificationChannelBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) // For Newer API

                    .setSmallIcon(currentapiVersion)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setWhen(System.currentTimeMillis())
                    .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setContentIntent(orderIntent);

            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);

            channel.enableLights(true);
            channel.setLightColor(Color.BLUE);
            channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            channel.enableVibration(true);
            channel.setDescription("Plan Notification");
            notificationManager.createNotificationChannel(channel);
            notificationManager.notify((int) notificationId, notificationChannelBuilder.build());

        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)//for older API

                    .setSmallIcon(currentapiVersion)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .setWhen(System.currentTimeMillis())
                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setContentIntent(orderIntent);

            notificationManager.notify((int) notificationId, notificationBuilder.build());
        }
    }

1 Ответ

1 голос
/ 02 июля 2019

Я был в той же проблеме в новом Api (28).Для более нового Api в NotificationCompat.Builder есть два параметра.Итак, я использовал Notification таким образом и работает как брелок:

 private static final String CHANNEL_ID = "nazim_borac_driver_channelId";

private void showNotificationSystemTray(String msg, String pickupLocation, String dropOffLocation) {


        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        long notificatioId = System.currentTimeMillis();

Intent openMain = new Intent(this, MainActivity.class);
        openMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        openMain.putExtra("checkNotification", "openOrder");

        PendingIntent contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), openMain, PendingIntent.FLAG_UPDATE_CURRENT);

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
            currentapiVersion = R.mipmap.ic_pickup;
        } else{
            currentapiVersion = R.mipmap.ic_launcher;
        }


      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


            NotificationCompat.Builder notificationChannelBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) // For Newer API

                    .setSmallIcon(currentapiVersion)
                    .setContentTitle("FROM: "+ pickupLocation)
                    .setContentText("TO: "+ dropOffLocation)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("TO: "+ dropOffLocation))
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .setWhen(System.currentTimeMillis())
                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setContentIntent(contentIntent);

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "BoracNotification", NotificationManager.IMPORTANCE_HIGH
            );

            channel.enableLights(true);
            channel.setLightColor(Color.BLUE);
            channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            channel.enableVibration(true);
            channel.setDescription("FROM: "+ pickupLocation+",   TO: "+ dropOffLocation);
            mNotificationManager.createNotificationChannel(channel);
            mNotificationManager.notify((int) notificatioId, notificationChannelBuilder.build());
            turnScreenOn(0,getBaseContext());
        }else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)//for older API

                    .setSmallIcon(currentapiVersion)
                    .setContentTitle("FROM: "+ pickupLocation)
                    .setContentText("TO: "+ dropOffLocation)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("TO: "+ dropOffLocation))
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                    .setWhen(System.currentTimeMillis())
                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setContentIntent(contentIntent);

            mNotificationManager.notify((int) notificatioId, notificationBuilder.build());
            turnScreenOn(0, getBaseContext());

        }


    }

Включите экран:

public static void turnScreenOn(int sec, final Context context1) {

        final int seconds = sec;
        PowerManager pm = (PowerManager) context1.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = Build.VERSION.SDK_INT>=20? pm.isInteractive() :  pm.isScreenOn();
        if (!isScreenOn) {

            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
            wl.acquire(seconds * 10000);
            PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
            wl_cpu.acquire(seconds * 10000);


        }


    }

И наконец:

String orderFragment =null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(getIntent()!=null){
            orderFragment = getIntent().getStringExtra("checkNotification");

            if(orderFragment!=null){

                if (orderFragment.equals("openOrder")) {
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new OrderFragment(), null).commit();
                }else {
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
                }

            }else {
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
            }

        }else {
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
        }
...