Неправильная активность открывается при нажатии уведомления

#android #android-intent #android-activity #notifications

#Android #android-намерение #android-активность #уведомления

Вопрос:

После нажатия на уведомление открывается неправильная активность — основная активность приложения, но не моя целевая активность — NearPhotoActivity.

создание уведомления:

     public static Notification createNotification(Location location) {
        NotificationChannel mChannel = new NotificationChannel(
                "3000", "notification_channel", NotificationManager.IMPORTANCE_LOW);
        notificationManager.createNotificationChannel(mChannel);
        return buildNotification("Notification Title",
                "Notification Body",
                true,
                R.drawable.ic_mr_button_connecting_00_dark,
                createPendingIntent(NearPhotoActivity.class, location),
                mChannel);
    }
  

создание PendingIntent:

     private static PendingIntent createPendingIntent(Class destinationActivityClass, Location location) {
        Intent intent = new Intent(MyApplication.getAppContext(),
                destinationActivityClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("nearLocation", location);
        return PendingIntent
                .getActivity(MyApplication.getAppContext(),
                        0,
                        intent,
                        PendingIntent.FLAG_CANCEL_CURRENT);
    }
  

Активность, которая должна быть открыта:

 @RequiresApi(api = Build.VERSION_CODES.O)
public class NearPhotoActivity extends AppCompatActivity {
    private ImageView nearPhotoImageView;
    private TextView locationDescriptionTextView;

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

        onNewIntent(getIntent());


        nearPhotoImageView = findViewById(R.id.nearPhotoImageView);

        locationDescriptionTextView = findViewById(R.id.locationDescriptionTextView);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if(intent.getExtras().containsKey("nearLocation")) {
            Location location = (Location) intent.getExtras().getSerializable("nearLocation");
            //Address address = MyAppUtils.getLocation(location.getLatitude(),location.getLongitude());
            locationDescriptionTextView.setText("You are "   location.distanceTo(MyApplication.getCurrentLocation())   " meters");
        }
    }
}
  

Ответ №1:

Открывается неправильная активность, потому что вы установили MainActivity значение по умолчанию Mainfest при запуске приложения.

Вы должны добавить onNewIntent функцию MainActivity , но не в NearPhotoActivity .

MainActivity

 override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    receiveIntent(intent)
}

fun receiveIntent(intent: Intent?) {
   Location location = (Location) intent.getExtras().getSerializable("nearLocation");
   Intent i = newIntent(MainActivity.this,NearPhotoActivity.class)
   i.putExtra("location",location)
   startActivity(i)
}
  

Затем используйте getExtra , чтобы получить location NearPhotoActivity класс in.

Комментарии:

1. Нет смысла обрабатывать onNewIntent в моей MainActivity, потому что мне нужно больше в NearPhotoActivity, потому что location передает оттуда компонент TextView.

2. Я думаю, он вернется JSON вместо объекта location?

3. Нет, он вернет действительный объект Location, теперь все работает нормально.