Как обнаружить отправителя уведомления, отправленного NotificationManager, или определить, какое уведомление было щелкнуто в панели уведомлений?

1

Я работаю над приложением GPS. Мое приложение отключит уведомление NotificationManager, если пользователь войдет внутрь или за пределами предопределенной зоны. Мое приложение может запускать уведомление для обоих случаев.

Из onResume(), я всегда получаю последнее значение intent.setExtra() вместо значения намерения .setExtra для кликаемого уведомления.

  

Проблема заключается в том, как обнаружить пользователя, нажав на уведомление для внутренней зоны или внешней зоны? (Я хочу показать разные взгляды на разные случаи)

         

Можно ли добавить прослушиватель для уведомления?

  

Вот мой шпинат кода:

private void displayNotificationMessage(String message, boolean vibrate, boolean playSound, Intent contentIntent, String notificationTag)
{       

    Notification notification = new Notification(R.drawable.buslogo, message, System.currentTimeMillis());

    PendingIntent myPendingIntent = PendingIntent.getActivity(this.getBaseContext(),0, contentIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(this, "Friendly Reminder", message, myPendingIntent);

    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);

    if (vibrate)
        notification.vibrate=new long[] {100L, 100L, 200L, 500L};

    if (playSound)
        notification.defaults |= Notification.DEFAULT_SOUND;


    notification.number = ++notificationCounter;
    notificationMgr.notify(notificationTag, notificationCounter, notification);

}

@Override
protected void onNewIntent( Intent intent ) {
    Log.i( TAG, "*********** onNewIntent(), intent = " + intent );
    if (intent.getExtras() != null)
    {
        Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
    }
    super.onNewIntent( intent );
    setIntent( intent );
}

@Override
public void onResume() {
    super.onResume();
    Log.i(TAG, "*********** Main - onResume()");

    Intent intent = this.getIntent();
    if (intent.getExtras() != null)
    {
        Log.i(TAG, "test = " + intent.getExtras().getString("test"));
    }
}

public void createNotification(String msnContent)
{
    Intent intent = new Intent();
    intent.setClass(this, Main.class);
    Bundle bundle = new Bundle(); 
    bundle.putString("test", msnContent);
    intent.putExtras(bundle);
    displayNotificationMessage(msnContent, true, true, intent, "test"); 

}
Теги:
notifications

2 ответа

2
Лучший ответ

Можно ли добавить прослушиватель для уведомления?

Используйте другой PendingIntent для каждого случая. Если вы только меняете лишний, не забудьте использовать FLAG_UPDATE_CURRENT при создании PendingIntent.

  • 0
    Спасибо, я изменил свой код. Я передаю новый объект PendingIntent наtification.setLatestEventInfo () каждый раз, прежде чем отправлять уведомление с помощьюtificationMgr.notify (). Но он по-прежнему не может отличить, какое уведомление на панели уведомлений было нажато. Поскольку onResume () всегда возвращает самое последнее значение setExtra ().
  • 0
    Есть ли способ передать значение / объект из исходного действия в намерение, вызываемое уведомлением?
Показать ещё 6 комментариев
0

Я нашел решение из этого сообщения - Неполадка при запуске нового действия с PendingIntent. Кроме того, благодаря помощи CommonsWare.

Мне не хватало намерения .setAction().

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

package com.NotificationTest;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {
    private static final String TAG = Main.class.getSimpleName();
    int notificationCounter =0;
    private NotificationManager notificationMgr;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        notificationMgr =(NotificationManager)getSystemService(
                NOTIFICATION_SERVICE);

        notificationMgr.cancelAll();

        Button b1 = (Button) findViewById(R.id.b1);
        b1.setText("B1");
        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                createNotification("From B1");
            }
        });


        Button b2 = (Button) findViewById(R.id.b2);
        b2.setText("B2");
        b2.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                createNotification("From B2");
            }
        });
    }


    private void displayNotificationMessage(String message, boolean vibrate, boolean playSound, Intent contentIntent, String notificationTag)
    {       

        Notification notification = new Notification(R.drawable.icon, message, System.currentTimeMillis());


        contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent myPendingIntent = PendingIntent.getActivity(this.getBaseContext(),0, contentIntent,PendingIntent.FLAG_UPDATE_CURRENT);


        notification.setLatestEventInfo(this, "Friendly Reminder", message, myPendingIntent);



        /*if (vibrate)
            notification.vibrate=new long[] {100L, 100L, 200L, 500L};

        if (playSound)
            notification.defaults |= Notification.DEFAULT_SOUND;*/


        notification.number = ++notificationCounter;
        notificationMgr.notify(notificationTag, notificationCounter, notification);

    }

    @Override
    protected void onNewIntent( Intent intent ) {
        Log.i( TAG, "*********** onNewIntent(), intent = " + intent );
        if (intent.getExtras() != null)
        {
            Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
        }
        super.onNewIntent( intent );
        setIntent( intent );
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "*********** Main - onResume()");

        Intent intent = this.getIntent();
        if (intent.getExtras() != null)
        {
            String extraOfClickedNotification = intent.getExtras().getString("test");

            Log.i(TAG, "test = " + extraOfClickedNotification);

            if (extraOfClickedNotification.equals("From B1"))
            {
                // Do something
            }
            else if (extraOfClickedNotification.equals("From B1"))
            {
                // Do something
            }
        }
    }

    public void createNotification(String msgContent)
    {
        Intent intent = new Intent();
        intent.setAction(msgContent + System.currentTimeMillis());
        intent.setClass(this, Main.class);
        Bundle bundle = new Bundle(); 
        bundle.putString("test", msgContent);
        intent.putExtras(bundle);
        displayNotificationMessage(msgContent, true, true, intent, "test"); 

    }

}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню