Android 尝试在推送通知单击时打开片段。不起作用

Android 尝试在推送通知单击时打开片段。不起作用,android,firebase,push-notification,Android,Firebase,Push Notification,我试图通过firebase中触发的推送通知打开一个片段。它不起作用。下面是MessageService.java private void showNotification(String title, String body) { String NOTIFICATION_CHANNEL_ID = "plan.services.test"; Intent openMain = new Intent(this, MainActivity.class);

我试图通过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());
        }
    }
下面是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());
        }
    }

我在新的Api(28)中遇到了同样的问题。对于较新的Api,NotificationCompat.Builder中有两个参数。 所以,我用这种方式通知,效果很好:

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

我更新了我的代码十几次,从字面上复制了你的代码,当我试图在主活动中检索它时,意图中的额外代码仍然是空的。我甚至不知道如何调试它在这一点上。好的,明白了,根据你的评论,我已经编辑了我的答案,请检查它。你测试我的完整编辑的答案吗?我已经测试过了,它可以工作了。请再次尝试我的完整答案。将修改后的代码粘贴到上面。这很有效,但我不知道为什么。除了可提取资产,我什么都不碰。感谢您的耐心。原因有两个:1)最新的notification compat builder有两个参数,2)您的字符串额外名称是“checkNotification”,因此请使用“checkNotification”,而不是“openOrder”。