FCM Нажмите, чтобы открыть задание, указанное пользователем, вместо действия по умолчанию, когда приложение находится в фоновом режиме. - PullRequest
0 голосов
/ 13 марта 2019

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

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

Вот MyFirebaseMessagingService Класс:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    private String title, messageBody;

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
                title = remoteMessage.getData().get("title");
                if (TextUtils.isEmpty(title)) title = "Bocawest";
                messageBody = remoteMessage.getData().get("message");
            }
            handleNow();
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        if (!TextUtils.isEmpty(messageBody))
            sendNotification(title, messageBody);
        //sendNotification(remoteMessage.getNotification().getBody());
        Intent intent = new Intent();
        intent.setAction("com.android.bocawest");
        sendBroadcast(intent);
    }
    // [END receive_message]

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String title, String messageBody) {
        PendingIntent pendingIntent;
        if (SharedPreference.getBoolean(getApplicationContext(), getApplicationContext().getResources().getString(R.string.sp_isLoginIN))) {
            Intent intent = new Intent(this, NotificationsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        }


        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(title)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Bocawest",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

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

Примечание: NotificationsActivity - это мое указанное действие. HomeActivity по умолчанию

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

Ответы [ 3 ]

0 голосов
/ 14 марта 2019

if (SharedPreference.getBoolean (getApplicationContext (), getApplicationContext (). GetResources (). GetString (R.string.sp_isLoginIN))) записать эту логику в HomeActivity (в onCreate () перед setContentView ()) поэтому каждый раз, когда пользователь будет перенаправлен на HomeActivity , и, если вышеуказанное условие удовлетворяет, пользователь будет перенаправляться снова на NotificationsActivity , в противном случае будет продолжено с HomeActivity

check - Для перехода к различным действиям при уведомлении нажмите

0 голосов
/ 14 марта 2019

это работает для меня - просто добавьте код ниже onMessageReceived()

Intent intent = new Intent(this, NotificationsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "111")
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.yhnn))
.setContentText(title)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSound(sound)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(5, builder.build());
0 голосов
/ 13 марта 2019

@ Laxman parlapelly согласно Firebase standered когда ваше приложение получит уведомление в фоновом режиме и пользователь нажмет на уведомление, тогда оно откроет только действие по умолчанию.Если вы хотите открыть указанное действие, тогда вам нужно пройти только действие по умолчанию.

Например, в вашем случае, когда пользователь нажмет на уведомление, оно откроет ваше домашнее действие, и из нового метода HomeActivity вам нужноopen NotificationsActivity (вместе с необходимыми пакетами)


Когда

Уведомление касается, когда приложение находится в фоновом режиме, тогда onCreate () метод HomeActivity будет вызываться такс тем, что вы можете написать код, чтобы открыть Notification Activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        animLay = findViewById(R.id.root_lay_la);
        Intent intent = new Intent(this,NotificationActivity.class);
        //intent.putExtra("KEY",getIntent().getStringExtra("data")); if u need to pass data
        startActivity(intent);
    }
...