Отправка пользователя на определенную страницу из уведомления

Я создаю приложение для Android, у меня есть уведомления, работающие с использованием функций firebase и службы обмена сообщениями firebase. В настоящее время я ищу уведомление для отправки пользователя на определенную страницу в зависимости от уведомления. Я начал делать это, передавая данные с уведомлением, которое устанавливает намерение, которое помещается в ожидающее намерение, которое устанавливается как контентное намерение в построителе уведомлений, как в приведенном ниже коде.

MyFirebaseMessagingService.java

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconcrossroadscwhite))
            .setSmallIcon(R.drawable.iconcrossroadscwhite)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri);


    Intent notificationIntent = null;

    if (tag.equals("acceptBidNotification"))
    {
       notificationIntent = new Intent(MyFirebaseMessagingService.this, SplashScreen.class);
       notificationIntent.putExtra("menuFragment", "myJobsFragment");
       notificationIntent.putExtra("tabView", "Active");
    }
    else if (tag.equals("newBidNotification"))
    {
        notificationIntent = new Intent(MyFirebaseMessagingService.this, SplashScreen.class);
        notificationIntent.putExtra("menuFragment", "myAdvertsFragment");
        notificationIntent.putExtra("tabView", "Pending");
    }
    else if (tag.equals("jobCompletedNotification"))
    {
        notificationIntent = new Intent(MyFirebaseMessagingService.this, SplashScreen.class);
        notificationIntent.putExtra("menuFragment", "myAdvertsFragment");
        notificationIntent.putExtra("tabView", "Completed");
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    notificationBuilder.setContentIntent(pendingIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);



    notificationManager.notify(count, notificationBuilder.build());
    count++;

Затем это переходит на экран-заставку, поскольку я обнаружил, что если я передал его другому моему основному классу, который содержал все фрагменты приложений, он переопределил его после и просто запустил приложение как обычно и перешел к «Найти задание» Страница. Затем я создал этот метод в SplashScreen.java, который проверяет, содержит ли пакет информацию, и, если она есть, отправляет ее на указанную страницу. Однако по какой-то причине кажется, что экран-заставка запускается перед запуском кода обмена сообщениями, который устанавливает эту информацию. Следовательно, это означает, что пакет пуст или содержит информацию, которая не является правильным пакетом, что означает, что необходимая информация равна нулю.

SplashScreen.java

public class SplashScreen extends AppCompatActivity {


private GifImageView gifImageView;
private String menuFragment, tabView;
private Bundle newBundle;


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

    Bundle bundle = getIntent().getExtras();
    if (bundle != null)
    {
        menuFragment = bundle.getString("menuFragment");
        tabView = bundle.getString("tabView");
    }

    gifImageView = (GifImageView)findViewById(R.id.gifImageView);


    try{
        InputStream inputStream = getAssets().open("crossroadssplash.gif");
        byte[] bytes = IOUtils.toByteArray(inputStream);
        gifImageView.setBytes(bytes);
        gifImageView.startAnimation();
    }
    catch (IOException ex)
    {

    }

    new Handler().postDelayed(new Runnable() {
        public void run() {
            if (menuFragment != null && tabView != null)
            {
                if (menuFragment.equals("myJobsFragment"))
                {
                    newBundle = new Bundle();
                    newBundle.putString("tabView", tabView);
                    MyJobsFragment myJobsFragment = new MyJobsFragment();
                    myJobsFragment.setArguments(newBundle);
                    getFragmentTransaction().replace(R.id.content, myJobsFragment).commit();

                }
                else if (menuFragment.equals("myAdvertsFragment"))
                {
                    newBundle = new Bundle();
                    newBundle.putString("tabView", tabView);
                    MyAdvertsFragment myAdvertsFragment = new MyAdvertsFragment();
                    myAdvertsFragment.setArguments(newBundle);
                    getFragmentTransaction().replace(R.id.content, myAdvertsFragment).commit();
                }
            }
            else {
                SplashScreen.this.startActivity(new Intent(SplashScreen.this, LoginActivity.class));
                SplashScreen.this.finish();
            }
        }
    }, 7000);
}
private FragmentTransaction getFragmentTransaction()
{
    final android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    return fragmentTransaction;
}

}

При необходимости может быть предоставлен любой дополнительный код. Спасибо

Это вне контекста, но вы показываете свой экран-заставку в течение 7 секунд? Это слишком много.

Kunu 23.04.2018 13:37

Да, я знаю, это проблема, которую я изменяю, ты не думаешь, что 7 секунд - это долгое время, пока ты не сядешь и не увидишь это постоянно хахахаха

Oliver McBurney 23.04.2018 13:38

ваше приложение находится на переднем плане или в фоновом режиме при получении этого уведомления?

Ashwani 23.04.2018 15:35

Если он находится в фоновом режиме, процедура отличается, если на переднем плане, тогда будет работать простая startActivity с намерениями.

Ashwani 23.04.2018 15:36
0
4
102
0

Другие вопросы по теме