i see many post on stackoverflow but i can't find a fix to my problem.
I have a notification with a custom content view with a button linked with a RemoteViews. I followed this link (Adding button action in custom notification) for attach an action to my button, but my BroadcastReceiver is never fired. The code:
private void createNotification(int index){
final int id = index;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setInt(R.id.container,"setBackgroundColor",ContextCompat.getColor(this,BG_COLORS[index]));
contentView.setImageViewResource(R.id.logo,BUTTON_OFF[index]);
contentView.setTextViewText(R.id.sound, getString(SOUND_NAME[index]) );
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(contentView);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, id, notificationIntent, 0);
Notification notification = mBuilder.build();
notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent closeButton = new Intent(this,StopReceiver.class);
closeButton.setAction(StopReceiver);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, closeButton,0);
contentView.setOnClickPendingIntent(R.id.stop,pendingIntent);
mNotificationManager.notify(id, notification);
}
public static class StopReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Never called
Log.d(LOGTAG,"Received Cancelled Event");
...
}
}
I have also declared my receiver in my AndroidManifest.xml:
<receiver android:name="StopReceiver" android:enabled="true" />
Thank you.
You are setting the setOnClickPendingIntent of the RemoteViews after supplying it as the custom RemoteView of the Notification.
Try setting setOnClickPendingIntent before calling setContent. E.g.:
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setInt(R.id.container,"setBackgroundColor",ContextCompat.getColor(this,BG_COLORS[index]));
contentView.setImageViewResource(R.id.logo,BUTTON_OFF[index]);
contentView.setTextViewText(R.id.sound, getString(SOUND_NAME[index]) );
Intent closeButton = new Intent(this,StopReceiver.class);
closeButton.setAction(StopReceiver);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, closeButton,0);
contentView.setOnClickPendingIntent(R.id.stop,pendingIntent);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(contentView);
If you are using listview in widget then it is very costly to set PendingIntents on the individual items, and is hence not permitted. Instead a single PendingIntent template can be set on the collection, you can use setOnClickFillInIntent()
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_article_list_item);
Intent intent = new Intent(context, ArticleDetailActivity.class); //activity to start
intent.putExtra("article",articleList.get(position));//any data to send
//don't use pending intent here
views.setOnClickFillInIntent(R.id.widget_item, intent);
You can use this in overridden method getViewAt(final int position) { ... }
Related
i'm developing addAction notification from iBeacon, how do i give boolean status success or not to this actionIntent from this pendingIntent notification which will received in onReceive method in ActionReceiver.class
this is the notification method from MainActivity.class
Intent broadcastIntent = new Intent(this, ActionReceiver.class);
broadcastIntent.putExtra("action", "notif1");
PendingIntent actionIntent = PendingIntent.getBroadcast(
this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.th_notif_logo)
.setTicker("Your Title")
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.addAction(R.drawable.ic_petunjuk_icon,"Clue", actionIntent)
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setStyle(new Notification.BigTextStyle().bigText(message))
.setContentIntent(pIntentAction)
.setPriority(Notification.PRIORITY_HIGH)
.build();
this is the onReceive method in ActionReceiver.class
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getStringExtra("action");
if(action.equals("notif1")){
SharedPreferences preferences = context.getSharedPreferences("MYPREFS", MODE_PRIVATE);
final String nama_tim = preferences.getString("username", "Key not correct");
InserData(nama_tim, "fsrd");
Toast.makeText(context.getApplicationContext(),"Action Receiver berhasil masuk",Toast.LENGTH_SHORT).show();
}
else if(action.equals("action2")){
}
//This is used to close the notification tray
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
}
so when i got boolean status success or not, i can do something in MainActivity.class
if (actionIntent == success){
//do something
}
really appreciate your help guys..
On your MainActivity.class
Intent broadcastIntent = new Intent("action-key"); // Specify the action to your intent.
broadcastIntent.setPackage(getPackageName());
// The values you want receive in the BroadcastReceiver.
broadcastIntent.putExtra("key-action", "notif1");
broadcastIntent.putExtra("key-boolean", true);
PendingIntent actionIntent = PendingIntent.getBroadcast(
this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT)
NotificationCompat.Action notificationAction = new NotificationCompat.Action(R.drawable.ic_action, "Action Name", actionIntent)
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(this,"channelId")
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Your Title")
.setWhen(System.currentTimeMillis())
.setContentTitle("test")
.setContentText("test")
.setAutoCancel(true)
.addAction(notificationAction) // Adds an action button to the notification
.setContentIntent(contentIntent) // Launches the intent when you click the notification.
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setPriority(Notification.PRIORITY_HIGH)
.build();
....
....
// Instead of using your own class receiver, you have to use the default default class receiver if you want your data to reach to your MainActivity.class easily.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == "action") {
bool result = intent.getBooleanExtra("key-boolean", false); // Your value
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("action");
registerReceiver(broadcastReceiver, intentFilter);
Have you tried using public static boolean? Can you explain exactly when do you want your boolean to be true or false?
So i have an alarm app...and when the receiver gets an intent from an alarm class, it creates a notification and builds it..but i just cant seem to figure out how to add onclick event to that button..i want it to implement a function not to just get an intent
this is my receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Context context= arg0;
Intent intent = new Intent(context,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent,0);
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.mini)
.setContentTitle(context.getResources().getString(R.string.message_box_title))
.setContentText(context.getResources().getString(R.string.message_timesheet_not_up_to_date))
.addAction(R.drawable.bell,"snooze",pendingIntent);
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
Integer get_your_alarm_choice = arg1.getExtras().getInt("alarm_choice");
Log.e("alarm choice is",get_your_alarm_choice.toString());
}
any help would be really appreciated
I think you want to add a custom button in your notification and want to click it.
Please try below code if you need the same:
You have to use RemoteViews for this.
I have created one custom layout named notification_normal_view.xml.
In my notification_normal_view , I have one TextView i.e.txtSnooze and on click I want to open SnoozeActivity and if I click at any other part of notification I want to open MainActivity.
So in your receiver :
// Using RemoteViews to bind custom layouts into Notification
RemoteViews notificationView = new RemoteViews(context.getPackageName(), R.layout.notification_normal_view);
Intent snoozeIntent = new Intent(context, SnoozeActivity.class);
snoozeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK | Notification.FLAG_AUTO_CANCEL);
PendingIntent pSnoozeIntent = PendingIntent.getBroadcast(context,NOTIFICATION_ID,snoozeIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Intent intent = new Intent(context, ExoVideoPlayer.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK | Notification.FLAG_AUTO_CANCEL);
PendingIntent pIntent = PendingIntent.getActivity(context, NOTIFICATION_ID,intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationView.setOnClickPendingIntent(R.id.txt_snooze, pSnoozeIntent);
Notification notificationBuilder = new Notification.Builder(context)
.setSound(soundUri)
.setSmallIcon(icon)
.setAutoCancel(true)
.build();
//set your view to notification
notificationBuilder.contentView = notificationView;
notificationBuilder.flags = Notification.FLAG_AUTO_CANCEL;
notificationBuilder.icon = R.mipmap.ic_launcher;
notificationBuilder.contentIntent = pIntent;
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, notificationBuilder);
i have a notification which i'm calling from a service. I want to call the service again on notification click. But the notification click is not able to get inside the method.
Intent intent = new Intent(this, MyService.class).setAction(ACTION_1);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.food)
.setContentTitle("notification")
.setContentText("near by you!");
NotificationManager mNotificationManager =(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Method that i want to call is
if (ACTION_1.equals(resultPendingIntent)) {
getRecommendation();
}
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager.notify(id, mBuilder.build());
i have tried following link but not able to resolve my problem.
How to execute a method by clicking a notification
You can specify a Broadcast in your Service and launch that via a PendingIntent in your notification.
Intent stopIntent = new Intent("my.awersome.string.name");
PendingIntent stopPi = PendingIntent.getBroadcast(this, 4, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Then, in your notification builder:
NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context)
...
.setContentIntent(stopPi);
In your Service you can setup a BroadcastReceiver as:
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Code to run
}
};
You register this receiver in your Service (possibly in onStartCommand()) only using:
registerReceiver(myReceiver, new IntentFilter("my.awersome.string.name"));
Your Service MUST be running for this to work.
Better option is to try How to execute a method by clicking a notification ..but be careful because of the static class
I use below code how to achieve my motto, I want to close or clear notification from notification bar click on close button
Intent moreNewsIntent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(AppService.this, 0, moreNewsIntent, 0);
// expanded view of the notification.
/* Intent close = new Intent(this, AppService.class);
close.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, close, 0);*/
int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, AppService.this);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setTicker("News Notification")
.setContentText(getString(R.string.lbl_notification_title_news))
.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE)
.setLights(0xff00ff00, 300, 100)
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setContentIntent(pIntent)
.addAction (R.drawable.news_negative,getString(R.string.btn_more_nes), pIntent)
.addAction (R.drawable.close,getString(R.string.btn_close), dismissIntent)
.setAutoCancel(true);
NotificationActivity.java
public class NotificationActivity extends Activity {
public static final String NOTIFICATION_ID = "001";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
finish(); // since finish() is called in onCreate(), onDestroy() will be
// called immediately
}
public static PendingIntent getDismissIntent(int notificationId,
Context context) {
Intent intent = new Intent(context, NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(NOTIFICATION_ID, notificationId);
PendingIntent dismissIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
return dismissIntent;
}
}
AndroidManifest.xml
<activity android:name=".NotificationActivity" android:taskAffinity="" android:excludeFromRecents="true">
Thanx in advance help would be greatly appreciated
Call cancel() with the same id you initialized the notification with.
If you are asking how to get a PendingIntent to do a cancel() call, it looks like you were on the right track with PendingIntent.getService(). A better approach would probably be to use PendingIntent.getBroadcast(), register a receiver in the manifest, and do the call from there.
I have created a custom layout notification using remoteview. Problem I'm facing is, How to autoCancel the notification once the user touches it.
I did try few things, but none is giving desired result.
Find Code below:
RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.notification_layout);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setSmallIcon(R.drawable.ic_launcher);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, RQST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
remoteView.setOnClickPendingIntent(R.id.btnNotification, pIntent);
builder.setAutoCancel(true);
builder.setContent(remoteView);
Notification notify = builder.build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notiManager.notify(NOTY_ID, notify);
For others who have a custom layout and want auto cancel to work,
If clicking anywhere on notification is ok, then don't use remoteView.setOnClickPendingIntent. Because any view with OnClick Listener overrides the notification main OnClick Listener.
Use setContentIntent instead:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("title");
builder.setContentText("contect");
builder.setSmallIcon(#smallicon);
builder.setWhen(#when);
builder.setContent(remoteViews);
builder.setContentIntent(onClickPendingIntent); // use this
builder.setAutoCancel(true);
The way I achieved this is by creating BroadcastReceiver which controls button clicks from Notification. Create something like this :
public class NotificationButtonListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int action = intent.getIntExtra("mode", -1);
switch (action) {
// do some things depending on action if there are more stuff to do
}
}
}
Don't forget to add your BroadcastListener to your manifest file:
<receiver android:name=".NotificationButtonListener">
And you can create a helper class for creating and cancelling notification:
public class NotificationHelper {
private static final int NOTIFICATION_ID = 5;
private static NotificationManager mNotificationManager = null;
public static void showNotification(Context context) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
contentView.setOnClickPendingIntent(R.id.btn_close, closePendingIntent);
Intent mMainIntent = new Intent(context, MainActivity.class);
mMainIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent mMainPendingIntent = PendingIntent.getActivity(context, 555, mMainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setTicker("Playing")
.setContent(contentView)
.setAutoCancel(false)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_av_play)
.setContentIntent(mMainPendingIntent);
Notification notification = mBuilder.build();
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
public static void cancelNotification() {
if (mNotificationManager != null) {
mNotificationManager.cancelAll();
}
}
}
And using that class in your NotificationButtonListener you can call NotificationHelper.cancelNotification(); .
Hope this helps you!