tags:

views:

60

answers:

2

I would like to know if there is a way of using the notication bar in order to do some operations (onClick), without having an activity being launched/resumed.

for example.. let's say i raise a notifcation, and when the user press on it, then instead of take me to some activity, it invoke some regular method in my current activity/service

Is there any way to implement such a thing?

for example the current notifcation code do a standart behave onClick. running up an activity.. how will channge the code in order to invoke some method instead of an activity?

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


    Notification notification = new Notification(R.drawable.icon, message,
            System.currentTimeMillis());
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, someActivity.class), 0);
    notification.setLatestEventInfo(context, "notification", message,
            contentIntent);
    messagesManager.notify(R.string.noto, notification);
A: 

I don't believe this is possible or, at the very least, best practice. It's possible that Android could kill your activity while the Notification is still waiting in the top bar. For example maybe you get a phone call but Android is low on RAM - it kills your activity, thus there's really not a 'current' activity anymore.

Colin O'Dell
+1  A: 

Is there any way to implement such a thing?

Use an appropriate PendingIntent. Instead of calling getActivity(), call getService() or getBroadcast().

CommonsWare
How would getService or getBroadcast will help me to invoke a regular method? could you show me some sample of such a pending intent?
Moshik
In the `BroadcastReceiver` or `Service` (as opposed to `Activity`) launched by clicking the notification, that's where you could "invoke some method".
Christopher
Yes, but how will i invoke a method,(through the notification bar) in the same service which raised that notice? is they any method i could override in that service when getService being called from the notification manager(and from there i could navigate to my target method)
Moshik
"Yes, but how will i invoke a method,(through the notification bar) in the same service which raised that notice?" `onStart()` in your `Service` or `onReceive()` in your `BroadcastReceiver` detects the `Intent` sent by the `PendingIntent` and calls your desired method.
CommonsWare
You said, onStart() will be invoked in the same service which raised the notice, but if that service is already working in the background.. why onStart() would work? thanks.
Moshik
@Moshik: Because `onStart()` gets called *every* time `startService()` gets called. `onCreate()` will only be called once, when the service is initialized.
CommonsWare