Метод вызова Android при нажатии уведомления - программирование
Подтвердить что ты не робот

Метод вызова Android при нажатии уведомления

Этот код создает уведомление. Если вы нажмете его, текущее приложение будет запущено (намерение создается в Entry, что является моим единственным Activity), слегка измененной версией блога разработчиков Android:

private void makeIntent() {
    NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification note = new Notification(R.drawable.prev, "Status message!", System.currentTimeMillis());
    Intent intent = new Intent(this, Entry.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
    note.setLatestEventInfo(this, "New Email", "Unread Conversation", pi);
    note.flags |= Notification.FLAG_AUTO_CANCEL;
    mgr.notify(NOTIFY_ME_ID, note);
}

Но я не хочу начинать какие-либо действия, а просто запускать метод в текущей деятельности. Из того, что я читал до сих пор, я предполагаю, что мне нужно использовать такие методы, как startActivityForResult(), использовать intent-filters и реализовать onActivityResult(), но после беспорядка со всеми этими вещами изменение вещей в Intent и PendingIntent, У меня все еще нет полезного результата. Можно ли как-то просто вызвать метод в Entry (мой основной Activity, в котором создан Intent) или уловить любой исходящий или входящий Intents, когда я нажимаю на мой новый Notification?

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

4b9b3361

Ответ 1

Добавьте android:launchMode="singleTop" в свой activity в файл манифеста, используйте метод protected void onNewIntent(Intent intent) { ... } и используйте этот код:

private static final int MY_NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private Notification myNotification;

void notification() {   
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    myNotification = new Notification(R.drawable.next, "Notification!", System.currentTimeMillis());
    Context context = getApplicationContext();
    String notificationTitle = "Exercise of Notification!";
    String notificationText = "http://android-er.blogspot.com/";
    Intent myIntent = new Intent(this, YourActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(YourActivity.this, 0, myIntent, Intent.FILL_IN_ACTION);
    myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    myNotification.setLatestEventInfo(context, notificationTitle, notificationText, pendingIntent);
    notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}

Ответ 2

Это работало на 100% для меня:

Поместите этот код в метод:

Intent intent = new Intent(this, YourClass.class);
    intent.putExtra("NotiClick",true);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        Notification Noti;
        Noti = new Notification.Builder(this)
                .setContentTitle("YourTitle")
                .setContentText("YourDescription")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true).build();

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, Noti);
    }

Затем в конструкторе onCreate/вашего класса выполните следующее:

if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if(extras == null) 
        {
            //Cry about not being clicked on
        } 
        else if (extras.getBoolean("NotiClick"))
        {
            //Do your stuff here mate :)
        }

    }

Ответ 3

    Intent intent = new Intent(this, Notificationintent.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);



    Notification noti = new Notification.Builder(this)
    .setContentTitle("APP NOTIFICATION")
    .setContentText(messageValue)
    .setSmallIcon(R.drawable.ic_launcher)
     .setStyle(new Notification.BigTextStyle()
     .bigText(messageValue))
    .setContentIntent(pIntent).build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;

notificationManager.notify(0, noti);