как перейти к конкретной активности при нажатии на уведомление? - PullRequest
0 голосов
/ 07 мая 2019

Есть несколько уведомлений и, нажав на уведомления, я хочу перейти к определенной деятельности.Скажем, появилось уведомление о вознаграждении, и, нажав кнопку, вы перейдете в раздел RewardActivity и добавите нового друга, а затем нажмите на уведомление о новом знакомстве, чтобы перейти в FriendlistActivity независимо от того, находится ли приложение на переднем или заднем плане.

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

private void handleDataMessage(String noti_title,String noti_message,String noti_click_action) {

    try {

        Intent intent = new Intent(this, RewardActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("title", noti_title);
        ByteArrayOutputStream _bs = new ByteArrayOutputStream();
        //image.compress(Bitmap.CompressFormat.PNG, 50, _bs);
        //intent.putExtra("img", image);
        intent.putExtra("msg", noti_message);
        intent.putExtra("click_action", noti_click_action);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new
                NotificationCompat.Builder(this, "Default")
                //.setLargeIcon(R.mipmap.ic_launcher)/*Notification icon image*/
                .setSmallIcon(R.mipmap.ic_launcher)
                //.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(Notification.PRIORITY_HIGH)
                .setChannelId("Default")
                .setVibrate(new long[]{1000, 1000})
                .setContentIntent(pendingIntent);

        notificationBuilder.setContentTitle(noti_title);
        notificationBuilder.setContentText(noti_message);
        notificationBuilder.setAutoCancel(true);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());



    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

1 Ответ

1 голос
/ 07 мая 2019

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

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

  2. Сообщения, содержащие как уведомления, так и данные, как в фоновом, так и в переднем плане .В этом случае уведомление доставляется в системный трей устройства, а полезная нагрузка данных доставляется в дополнениях намерения вашего средства запуска.

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

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

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

в моем средстве запуска AndroidManifest Действие - SplashActivity

<activity android:name=".activities.SplashActivity">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Вы можете протестировать уведомление на pushtry.com от Google FCM Tester.Вот формат данных для воспроизведения при отправке через pushtry.com

{
  "to":"your_device_token",
  "data": {
      "title": "hello",
      "message": "test message",
  },
 "priority":"high"
}

MyFirebaseMessagingService Class:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM Service";
    private static int count = 0;

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        KeyManager.setSharedPreferenceString(getApplicationContext(), "fcm_token", s);
        Log.e(TAG, "onNewToken: " + s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
//Here notification is recieved from server
        try {
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(getApplicationContext(), SplashActivity.class);  
//you can use your launcher Activity insted of SplashActivity, But if the Activity you used here is not launcher Activty than its not work when App is in background.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Add Any key-value to pass extras to intent
        intent.putExtra("pushnotification", "yes");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//For Android Version Orio and greater than orio.
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = new NotificationChannel("Sesame", "Sesame", importance);
            mChannel.setDescription(messageBody);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            mNotifyManager.createNotificationChannel(mChannel);
        }
//For Android Version lower than orio.
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "Seasame");
        mBuilder.setContentTitle(title)
                .setContentText(messageBody)
                .setSmallIcon(R.mipmap.ic_launcher_sesame)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_sesame))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setColor(Color.parseColor("#FFD600"))
                .setContentIntent(pendingIntent)
                .setChannelId("Sesame")
                .setPriority(NotificationCompat.PRIORITY_LOW);

        mNotifyManager.notify(count, mBuilder.build());
        count++;
    }

}

Теперь, когда вы получили pushnotification в фоновом режиме ищелкнув уведомление, уведомление доставляется в системный трей устройства, и дополнительные функции передаются на панель запуска Activity.Проверьте, запускается ли активность с дополнительными или пустыми, а затем перейдите к нужному пользователю.

, если вы хотите показать свою активность только зарегистрированному пользователю, а SplashActivity выглядит ниже:

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

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

        try {
            if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
                if (getIntent().hasExtra("pushnotification")) {
                    Intent intent = new Intent(this, YourDesiredActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    CheckLogin();
                }
            } else {
                Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }

        } catch (Exception e) {
            CheckLogin();
            e.printStackTrace();
        }
    }

    private void CheckLogin() {
        if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
            Intent i = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(i);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                }
            }, 2500);
        }
    }

}

Логика в SplashActivty для навигации пользователя в различных действиях в соответствии с условием.

Когда пользователь открывает приложение в обычном потоке, не нажимая на pushnotification, getIntent (). HasExtra («pushnotification») имеет значениеnull, поэтому команда переходит к блоку catch, а метод CheckLogin () проверяет наличие входа в систему или нет.Но пользователь вошел, нажав pushnotification, затем getIntent (). HasExtra («pushnotification») не является нулевым, и он перейдет к желаемому действию.

...