Откройте другое действие, отличное от MainActivity, при нажатии Firebase Notification - PullRequest
0 голосов
/ 30 сентября 2018

В моем приложении я хочу открыть пользовательские activity (не MainActivity ) и putExtra для этого activity при нажатии на Firebase уведомление.
Я пишу нижекоды, но при нажатии на уведомление открыть MainActivity , но я хочу открыть мой другой вид деятельности ( AuctionDetailActivity ).

Мой класс NotificationManager:

public class MyNotificationManager {

    private Context mCtx;
    private Uri soundUri;
    private static MyNotificationManager mInstance;

    public MyNotificationManager(Context context) {
        mCtx = context;
    }

    public static synchronized MyNotificationManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MyNotificationManager(context);
        }
        return mInstance;
    }

    public void displayNotification(String title, String body) {

        soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent intent = new Intent(mCtx, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("fcm_notification", "Y");

        PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setSound(soundUri)
                .setAutoCancel(true)
                .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                .setContentText(body)
                .setContentIntent(pendingIntent);

        NotificationManager mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);

        if (mNotifyMgr != null) {
            mNotifyMgr.notify(1, mBuilder.build());
        }
    }
}

И класс MyFirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        showNotify(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
    }

    private void showNotify(String title, String body) {
        MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
        //myNotificationManager.displayNotification(title, body);
        myNotificationManager.displayNotification(title, body);
    }
}

MainActivity коды:

@Override
protected void onResume() {
    super.onResume();
    String fcm_notification = getIntent().getStringExtra("fcm_notification");
    Log.d("FireBaseIntentLog", " FCM : " + fcm_notification);
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            String value = getIntent().getExtras().getString(key);
            Log.d("FireBaseIntentLog", "Key: " + key + " Value: " + value + " FCM : " + fcm_notification);
        }
    }
}

Как я могу это исправить?

Ответы [ 4 ]

0 голосов
/ 30 сентября 2018

Измените свой класс MyFirebaseMessagingService, как показано ниже, замените OtherApp.class именем вашей активности

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    Intent intent=new Intent(this,OtherApp.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);//newbg PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder= new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("FCM NOTIFICATION"); notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
    notificationBuilder.setContentIntent(pendingIntent);
    NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

   }
}
0 голосов
/ 30 сентября 2018

Если вы отправляете уведомление из консоли Firebase или из поля notification с помощью API FCM, приложение ведет себя двумя способами -

  • Если ваше приложение находится на переднем плане, метод onMessageReceived из вашего класса обслуживания FCM будет вызываться.
  • Если ваше приложение работает в фоновом режиме, то внутри вашего класса обслуживания FCM ничего не произойдет.Скорее, уведомление будет обрабатываться внутри самой библиотеки FCM, и будет отображаться уведомление с активностью запуска в намерении.

А если вы используете API FCM для отправки уведомления и используете dataВ этом случае библиотека сама ничего не делает и вместо этого вызывает метод onMessageReceived независимо от того, находится ли ваше приложение на переднем или заднем плане.

Таким образом, для решения вашей проблемы вы можете использовать одно из следующих двух решений:

  • Используйте API FCM для отправки уведомлений и используйте поле data вместо поля notification.Прочтите документацию , чтобы узнать больше об API FCM.

  • В своей активности запуска (основной) проверьте наличие намерения внутри onCreate и если оно исходит из уведомленияпрочитайте дополнительные материалы, завершите основное задание и откройте нужное задание.

Пример для второго случая:

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

    if (checkIntent()) return;

    // other code.
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    checkIntent();
}

private boolean checkIntent() {
    // to receive the value, send the value as custom data from Firebase console.
    String value = getIntent().getStringExtra("your_key");

    if (value == null) return false;

    if (value.equals("something")) {
        // open one activity.

    } else if (value.equals("another_thing")) {
        // open another activity.
    }

    finish();
    return true;
}
0 голосов
/ 30 сентября 2018

Вам просто нужно изменить в sendNotification функцию

public void sendNotification(String messageBody, String messageTitle, int user_id, String click_action) {
    Intent intent = new Intent(mCtx, AuctionDetailActivity.class); // Need modify this line
    intent.putExtra(Extras.bidID.name(), user_id);

    PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID);
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}
0 голосов
/ 30 сентября 2018

Измените эту строку ниже

Intent intent = new Intent(click_action);

на эту

Intent intent = new Intent(getActivity(), YourClass.class);
...