невозможно открыть активность из уведомлений - PullRequest
0 голосов
/ 29 апреля 2020

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

public class AlarmNotificationReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {

    sendNotification(context);

     }


public void sendNotification(Context context) {


    int NOTIFICATION_ID = 234;
    String CHANNEL_ID = "my_channel_01";

    Intent intent = new Intent(context, TestActivity.class);
    intent.putExtra("title", "Today,s Dish");
    intent.putExtra("getDetailShowId", 50);
    intent.setAction("MyIntent");
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);


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

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        //    String CHANNEL_ID = "my_channel_01";
        CharSequence name = "Title";
        String Description = "Its new";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mChannel.setDescription(Description);
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.RED);
        mChannel.enableVibration(true);
        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        mChannel.setShowBadge(false);
        notificationManager.createNotificationChannel(mChannel);



    }





    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Title")
            .setContentText("Its old")
            .setContentIntent(contentIntent)
            .setAutoCancel(true)
            ;

    Intent resultIntent = new Intent(context, MenuActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(resultPendingIntent);
    notificationManager.notify(NOTIFICATION_ID, builder.build());

}

Я не использую Oreo, так что забудьте об этом, и я получаю такие дополнения, но этот код не работает, он всегда открывает мою активность при запуске

toolbartitle = getIntent().getStringExtra("title");
    detailShowUrl = getIntent().getStringExtra("getDetailShowId");

1 Ответ

1 голос
/ 29 апреля 2020

TL; DR

  • Создать канал уведомлений
  • Создать уведомление
  • Вложить ожидающее намерение в уведомление, в котором вы будете добавить дополнительные данные
  • Когда щелкнет уведомление, pendingIntent запустит действие
  • Обработка того, что будет происходить внутри запущенного действия, основано на дополнительных данных ожидающего намерения

Некоторые код / ​​ресурсы для выполнения вышеуказанных шагов:

Как создать канал уведомлений:

Android O - Каналы уведомлений и NotificationCompat

Как создать pendingIntent:

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("data", json.toString());
intent.putExtra("has_extra_data", true);

PendingIntent pendingIntent = PendingIntent.getActivity(this, json.getInt("id") /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Как вставить pendingIntent в уведомление и показать его:

notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("title")
                        .setContentText("description")
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

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

Теперь добавьте это в MainActivity для обработки данных уведомления:

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (getIntent().getExtras().getBoolean("has_extra_data")){
        String data = getIntent().getExtras().getString("data");
        // Do what you want ...
        // You may want to start a new activity or show something in UI
    }
}

Примечание, основанное на вашем вопросе:

Если вы хотите открыть другое действие помимо MainActivity, вы должны сделать это, установив пользовательские переменные в дополнительные функции pendingIntent и разрешив MainActivit y, чтобы перенаправить вас в другой вид деятельности. По сути, MainActivity действует как маршрутизатор!

...