Implement setOnClickPendingIntent from notification - android

I build custom notification that contain button and i want to listin when user press on it.
The button should not open any activity but only logic staff like change song.
the Code:
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
contentView.setTextViewText(R.id.toptext, nowPlayingTitle);
//this not work
Intent intent = new Intent(this, receiver.class);
intent.putExtra("UNIQ", "1");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_CANCEL_CURRENT)
contentView.setOnClickPendingIntent(R.id.imageButtonPlay,
pendingIntent);
notification.contentView = contentView;
// this is to return to my activity if click somwhere else in notification
Intent notificationIntent = new Intent(this, MYACTIVITY.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
mNotificationManager.notify(NOTIFICATION_ID, notification);
I don't get the hang of the setOnClickPendingIntent what need to be in the second param?
How can i just call a function after user press on the button?
im probably missing something cause i dont understand the receiver side and what happend after user press

You are missing the fact that the button you created actually doesn't belong to your application. It is created in another context, in another process. There is no way it can call your function.
Instead, when the user taps the button, that pending intent is fired. You can catch it by your receiver (in your activity), check some parameters and do the action.
Or you can implement a service and handle this intent in background. I'd prefer this way.

thanks for quick answer. I try using receiver but it never fired.
The code is in the main question and i created for the reciever class the following code:
public class receiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
}
}
but click on the notification never fire the receiver ( Test on debug mode )

Related

onclicklistener for notification [duplicate]

This question already has answers here:
How to set click listener for notification?
(3 answers)
Closed 9 years ago.
I had set a notification in my app. Its working fine. If i click the notification in statusbar it takes to my app.
Now i need to set some work if the notification is clicked where can i set this?
Is there any method that implicitly got invoked when a notification is clicked?
Also i want to remove that notification if it is clicked,how to do so?
this is my code
notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent inty=getIntent();
note = new Notification(R.drawable.icon, "New E-mail", System.currentTimeMillis());
PendingIntent intent = PendingIntent.getActivity(MainActivity.this, 0, inty, 0);
note.setLatestEventInfo(MainActivity.this, "New E-mail", "You have one unread message.", intent);
notifManager.notify(R.string.search_hint, note);
You could add some extra data to the intent and then in your activity look for it in the onCreate and onNewIntent methods.
For example:
inty.putExtra("came from notification", true);
You can then read that out via the intent passed to onNewIntent or in onCreate by using getIntent().
intent.getBooleanExtra("came from notification", false);
Try to call broadcastReceiver it may helpful for your requirement,
Intent notificationIntent = new Intent(this, dummy_activity.class);
notificationIntent.setAction("android.intent.action.MAIN");
notificationIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT |
Notification.FLAG_AUTO_CANCEL);
// Now, once this dummy activity starts send a broad cast to your parent activity and finish the pending activity
//remember you need to register your broadcast action here to receive.
BroadcastReceiver call_method = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action_name = intent.getAction();
if (action_name.equals("call_method")) {
// call your method here and do what ever you want.
}
}
};
registerReceiver(call_method, new IntentFilter("call_method"));

How to detect if a notification has been dismissed?

Is there any way in Android to detect when a user swipes a notification to the left and deletes it? I'm using an alarmmanager to set a repeating alert and I need my repeating alert to stop when the notification is cancelled by the user. Here's my code:
Setting the repeating alert:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), repeatFrequency, displayIntent);
My notification code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the notification ID.
int notifID = getIntent().getExtras().getInt("Reminder_Primary_Key");
//Get the name of the reminder.
String reminderName = getIntent().getExtras().getString("Reminder_Name");
//PendingIntent stores the Activity that should be launched when the user taps the notification.
Intent i = new Intent(this, ViewLocalRemindersDetail.class);
i.putExtra("NotifID", notifID);
i.putExtra("notification_tap", true);
//Add FLAG_ACTIVITY_NEW_TASK to stop the intent from being launched when the notification is triggered.
PendingIntent displayIntent = PendingIntent.getActivity(this, notifID, i, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.flag_red_large, reminderName, System.currentTimeMillis());
CharSequence from = "Here's your reminder:";
CharSequence message = reminderName;
notif.setLatestEventInfo(this, from, message, displayIntent);
//Pause for 100ms, vibrate for 250ms, pause for 100ms, and vibrate for 500ms.
notif.defaults |= Notification.DEFAULT_SOUND;
notif.vibrate = new long[] { 100, 250, 100, 500 };
nm.notify(notifID, notif);
//Destroy the activity/notification.
finish();
}
I know I need to call alarmManager.cancel(displayIntent) in order to cancel my repeating alarm. However, I don't understand where to put this code. I need to cancel the repeating alert ONLY when the user has tapped on the notification or dismissed it. Thanks for your help!
I believe that Notification.deleteIntent is what you are looking for. The doc says:
The intent to execute when the notification is explicitly dismissed by the user, either with the "Clear All" button or by swiping it away individually. This probably shouldn't be launching an activity since several of those will be sent at the same time.
To all those future people out there -- you can register a broadcast receiver to listen for notification delete inents.
Create a new broadcast receiver:
public class NotificationBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null || !action.equals(Config.NotificationDeleteAction)) {
return;
}
// Do some sweet stuff
int x = 1;
}
}
Register the broadcast receiver within your application class:
"If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically)."
Android Documentation.
registerReceiver(
new NotificationBroadcastReceiver(),
new IntentFilter(Config.NotificationDeleteAction)
);
You probably noticed the static variable Config.NotificationDeleteAction. This is a unique string identifier for your notification. It typically follows the following {namespace}{actionName} convention:
you.application.namespace.NOTIFICATION_DELETE
Set the delete intent on your notification builder:
notificationBuilder
...
.setDeleteIntent(createDeleteIntent())
...
Where, createDeleteIntent is the following method:
private PendingIntent createDeleteIntent() {
Intent intent = new Intent();
intent.setAction(Config.NotificationDeleteAction);
return PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_ONE_SHOT
);
}
Your registered broadcast receiver should receive the intent when your notification is dismissed.
You can also use an Activity PendingIntent, which may be simpler to implement if you have an Activity that can handle the dismissal, because you don't have to create and configure a broadcast receiver.
public static final String DELETE_TAG = "DELETE_TAG";
private PendingIntent createDeleteIntent(Context context) {
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra(DELETE_TAG, true);
return PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_ONE_SHOT
);
}
MyActivity would receive the intent in its onCreate(), and in this example, could look for the DELETE_TAG extra to recognize it.

Custom status bar notification

I got a custom status bar notification. There is a "Play" and "Next" image on it.
I want to send a Broadcast Intent to a Service when the "play" or "next" image is pressed.
notification = new Notification(R.drawable.ic_launcher, title + "\n"
+ text, System.currentTimeMillis());
contentIntent = PendingIntent.getActivity(context, 0, actionOnClick, 0);
notification.contentIntent = contentIntent;
contentView = new RemoteViews(context.getPackageName(),
R.layout.custom_player_notification);
contentView.setTextViewText(R.id.custom_player_notification_title,
title);
contentView.setTextViewText(R.id.custom_player_notification_text, text);
notification.contentView = contentView;
This is the code.
The ContentView offers the possibility to set "setOnClickPendingIntent" and "setOnClickFillInIntent". How can I use them to send this broadcast?
I want to send a broadcast because I dont want to launch an activity.
I want to send a Broadcast Intent to a Service when the "play" or "next" image is pressed
I would suggest that you want to send a command via startService() rather than a broadcast.
How can I use them to send this broadcast?
You can try calling setOnClickPendingIntent(), supplying a PendingIntent you create via the static getBroadcast() method on PendingIntent (for a broadcast) or getService() (for a command to be sent via startService()).
Bear in mind that none of this will work on most Android devices available at present. I think buttons-in-Notifications works starting on Android 4.0, perhaps 3.0, but definitely not before then.
You could put something similar to this in your onClick() method of the notification, directing it to a broadcast receiver.
Intent intent = new Intent(this, receiver.class);
intent.putExtra("SomeInfoMaybe", info);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_CANCEL_CURRENT);
And then the code for handling the next stage could go in here:
public class receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("SomeInfoMaybe = " + bundle.getString("info"));
//etc...
}
}
calling .notify(); on your notification should help link to the broadcast receiver

Window already focused, ignoring focus gain of: com.android.internal.view

Unfortunately, I was unable to find a resolution to this issue in other StackOverflow posts so I apologize in advance for re-posting this question. Essentially, I have an AppWidget that creates a Notification. I want the user to click the Notification to launch an Activity. The AppWidget and Activity are in the same APK.
The following code is all in the AppWidget. Clicking on the Notification broadcasts a custom Intent which is received by the AppWidget.
The problem is that the Activity does not appear to launch, even though logcat demonstrates that the custom Intent has indeed been broadcast. The only clue is the logcat message reiterated in the post title.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Constants.BROWSER_INTENT)) {
launchActivity(context, R.layout.appwidget, R.id.launch_button, Activity.class);
}
super.onReceive(context, intent);
}
private void displayNotification(Context context, String ticker, String title, String msg) {
Intent intent = new Intent(context, ThisWidget.class);
intent.setAction(Constants.BROWSER_INTENT);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, ticker, System.currentTimeMillis());
notification.setLatestEventInfo(context, title, msg, pending);
notificationManager.notify(1, notification);
}
Some notes:
Pressing a button to execute launchActivity() works (it launches the
Activity)
launchActivity uses Intent.FLAG_ACTIVITY_NEW_TASK as
recommended by Android lifecycle documentation
Has anyone solved this issue when launching an Activity from a Notification press?
er, figures, I answered my own question just minutes after posting it. I guess I was over-complicating the implementation by using an Intent action. I changed these lines:
Intent intent = new Intent(context, ThisWidget.class);
intent.setAction(Constants.BROWSER_INTENT);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
to this:
Intent intent = new Intent(context, Activity.class);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
and it worked.
Sorry for the bogus post.

Android PendingIntent take you to an already existing activity?

Wasn't really sure how to search for this...
I have a the following which is called whenever a job is added or removed from my queue to put a notification in the status bar:
private void showNotification()
{
int jobsize = mJobQueue.size();
int icon = (jobsize == 0) ?
android.R.drawable.stat_sys_upload_done :
android.R.drawable.stat_sys_upload;
Notification notification =
new Notification(icon, "Test", System.currentTimeMillis());
Intent intent = new Intent(this, FileManagerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.flags =
(Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL);
notification.setLatestEventInfo(this,
"Uploading to our servers",
getString((jobsize > 0) ?
R.string.notification_active_transfers :
R.string.notification_no_transfers),
pendingIntent);
mNotifyManager.notify(NOTIFICATION, notification);
}
As it is now the behavior is this:
if the user logs out and hits the notification, it will still open a new FileManagerActivity (ops!) I could get around this by starting at my authentication activity and passing the intent up my stack in a natural order, its when the application is already running is where I have difficulties.
if the user already has the FileManagerActivity open clicking the notification will put a second instance over it. In this case, I want the currently running FileManagerActivity to recieve focus instead of launching a new instance.
How could I get the correct behavior?
I've done this before by setting my Activity to use the launch mode 'singleTop' in the Application Manifest. It will achieve the desired function, using the existing activity if one exists. In this case, onNewIntent will be called in your activity.
You'll need to check in your FileManagerActivity for authentication and start a new activity as appropriate if the user is not logged in.
I think Worked when added these:
intent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent.FLAG_UPDATE_CUR
Intent intent = new Intent(context, MyOwnActivity.class);
intent.putExtra("foo_bar_extra_key", "foo_bar_extra_value");
intent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent,PendingIntent.FLAG_UPDATE_CURRENT);

Categories

Resources