I am using pushbots with an android app. I have a custom broadcast receiver that handles notifications in the app. However, when I exit the app, all of the notifications are still there. How can I clear these notifications? I have tried the solutions on these questions:
How to clear a notification in Android
How to remove notification from notification bar programmatically in android?
but Im still not having any luck. Any suggestions?
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("CHAT", "RECIEVED");
Bundle notification = intent.getExtras();
String type = notification.getString("type");
//do some stuff here
NotificationManager nMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//nMgr.cancel();
nMgr.cancelAll();
Log.d("CHAT", "CANCEL");
}
};
Related
This question already has answers here:
Android notification .addAction deprecated in api 23
(6 answers)
Closed 5 years ago.
I'm creating a notification like this.
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle(notifyMessage1)
.setContentText(notifyMessage2)
.setSmallIcon(R.mipmap.ic_launcher);
Notification notification = builder.build();
I want to add a action to my notification with
builder.addAction();
To realize addAction(icon, title, pendingIntent); is deprecated
My geal is to create a notification action without an icon, how can i achieve that?
You can't directly call methods when you click action buttons.
You require to use PendingIntent with BroadcastReceiver or Service to perform this.
Here is an example of Pending Intent with Broadcast Reciever.
First build a Notification
public static void createNotif(Context context){
...
//This is the intent of PendingIntent
Intent intentAction = new Intent(context,ActionReceiver.class);
//This is optional if you have more than one buttons and want to differentiate between two
intentAction.putExtra("action","actionName");
pIntentlogin = PendingIntent.getBroadcast(context,1,intentAction,PendingIntent.FLAG_UPDATE_CURRENT);
drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.steeringwheel)
.setContentTitle("NoTextZone")
.setContentText("Driving mode it ON!")
//Using this action button I would like to call logTest
.addAction(R.drawable.smallmanwalking, "Turn OFF driving mode", pIntentlogin)
.setOngoing(true);
...
}
Now the receiver which will receive this Intent
public class ActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();
String action=intent.getStringExtra("action");
if(action.equals("action1")){
performAction1();
}
else if(action.equals("action2")){
performAction2();
}
//This is used to close the notification tray
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
}
public void performAction1(){
}
public void performAction2(){
}
}
Do not forget to declare BroadCast Receiver in Manifest
<receiver android:name=".ActionReceiver"></receiver>
Hope it helps you.
Use the NotificationCompat instead of Notification like this:
Notification.Action action = new NotificationCompat.Action(icon, title, pendingIntent);
Notification notification = new NotificationCompat.Builder(context)
.addAction(action)
.build();
I have an application which is basically a webview and GCM notifications. I want to achieve the following thing: If the user is in the app and receives a notification, when he clicks the notification I want the webview to load the url provided in the notification.
I'm trying to accomplish this by using broadcast receiver but it doesn't work.
I dynamically register the receiver in the MainActivity:
private void registerNotificationReceiver() {
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_LOAD_URL_FROM_NOTIFICATION);
Log.i(TAG, "registerNotificationReceiver()");
this.receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "notification received");
}
};
super.registerReceiver(this.receiver, filter);
}
And in the GCM Listener I'm using PendingIntent.getBroadast():
final Intent broadcastIntent = new Intent(MainActivity.ACTION_LOAD_URL_FROM_NOTIFICATION);
PendingIntent intent = PendingIntent.getBroadcast(getApplicationContext(), 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(intent);
notification = notificationBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
I don't understand why onReceive in the MainActivity class is not called. The message "notification received" is not displayed.
Can you help me? Thank you :)
I cannot find right now the reason but there's a security reason. Latest Android versions won't allow you to trigger a listener from "kind-of" remote process without it being explicit.
The intent you broadcast MUST be explicit for it to work. Explicit means that you have to explicitly call the component that will handle the intent (the receiver). So this receiver must be declared in its own class and in the manifest as a <receiver>.
Follow this guy's example in the section Explicit Broadcast Intents http://codetheory.in/android-broadcast-receivers/
and thy will be done.
I am developing an app wich receives GCM notifications to alert the user about promotions and stuff like that.
So far i have managed to send and receive notifications. Here is my code:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GCMNotificationIntentService extends IntentService {
public static final int notifyID = 1337;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
sendNotification(extras.getString("type"),extras.getString("msg"));
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String type, String msg) {
Intent resultIntent = new Intent(this, SplashActivity.class);
resultIntent.putExtra("type", type);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,resultIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("x")
.setContentText(msg)
.setSmallIcon(R.drawable.ic_launcher);
mNotifyBuilder.setContentIntent(resultPendingIntent);
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
mNotifyBuilder.setAutoCancel(true);
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
The problem is that i don't know how (or where) to show a message alert.
Searching on the web, i found an implementation where the message was shown even when the app was closed, but i only need to show the message on the app, for example: when the app is open or when the app is closed and the user opens it.
The Android notification framework is designed to show notifications irrespective of whether or not your app is open. Notifications are shown in the notification bar on the top and do not show within your activity screen.
If you do not want to show notifications when the app is not running, you can do something like have a variable isRunning and set it to true in onResume() of an activity and false in onPause() of an activity. This way, you now have a reference to find out if the app is running or not. If isRunning is false, then you can save the notifications that you are receiving in the background into a SharedPreferences or database - you will do this without using the Notification framework. If the app is open, then you can show a message alert - either using the Notification framework if that is what you intend to do or use an AlertDialog.
I am creating an notification by sending GCM message to my app using this code
private static void generateNotification(Context context, int type, String title, String message) {
Intent notificationIntent;
int icon = R.drawable.ic_launcher;
java.util.Random v = new java.util.Random();
int id = v.nextInt(1000);
long when = System.currentTimeMillis();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
notificationIntent = new Intent(context, Home.class);
notificationIntent.putExtra(CommonUtilities.TITLE_ALERT, title);
notificationIntent.putExtra(CommonUtilities.EXTRA_MESSAGE, message);
notificationIntent.putExtra(CommonUtilities.TYPE, type);
notificationIntent.putExtra(CommonUtilities.ID, id);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, type, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
Notification notification_view = notification.setContentTitle(title)
.setContentText(message).setContentIntent(intent)
.setSmallIcon(icon).setWhen(when)
.setVibrate(new long[] { 1000 }).build();
notification_view.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification_view.defaults |= Notification.DEFAULT_SOUND;
// notification_view.sound = Uri.parse("android.resource://" +
// context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification_view.defaults |= Notification.DEFAULT_VIBRATE;
manager.notify(id, notification_view);
}
and receiving this pending intent using receiver
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(!intent.hasExtra(CommonUtilities.TYPE)){
Log.v("msg", "intent vars not received");
return;
}
int type = intent.getExtras().getInt(CommonUtilities.TYPE);
String title = intent.getExtras().getString(CommonUtilities.TITLE_ALERT);
String newMessage = intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE);
String[] msgArr = newMessage.split(",");
Log.v("message", newMessage);
}
};
But my activity is not performing the action and showing me log. I have registered my receiver with a custom intent using
registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.DISPLAY_ACTION));
How can I find the error?
Edit
If application receives a notification while it is on foreground then notifications are received well but if the activity is not running or it is finished and I invoke it on notification click nothing happened
The code you have in generateNotification will only create a notification, not a broadcast.
Your Receiver won't ever receive anything because your'e never broadcasting. To utilize the receiver in the way you're using it you need to write code similar to this
public static final String DISPLAY_ACTION = "package.name.DISPLAY_MESSAGE";
public static final String EXTRA_MESSAGE = "message";
public static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
EDIT
I would add this code above to your CommonUtilities class, you also need to add this line to your generateNotification method
CommonUtilities.displayMessage(context, message);//this will then send your broadcast to the receiver.
EDIT - Show notification message when app is opened
I'm using similar functionality in my app. I saved the notification in a database as unread when it has been received by GCM and then alerted the user, as soon as the app is opened i checked for unread notifications and if found invoked the displayMessage method to show the user the missed notifications. After that I delete the notification from the db.
You wrote:
If application receives a notification while it is on foreground then
notifications are received well but if the activity is not running or
it is finished and I invoke it on notification click nothing happened
If you register your receiver from your activity by calling:
registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.DISPLAY_ACTION));
then you have registered the receiver using the context of the activity. That means that when the activity is finished, the registered receiver will be removed and destroyed (to prevent memory leaks).
If you want your receiver to be run even if your app is not running, then you need to register the receiver in the manifest, by adding an appropriate intent filter to your <receiver> definition:
<intent-filter>
<!-- use the correct name string for CommonUtilities.DISPLAY_ACTION) -->
<action android:name="blah.blah.blah.DISPLAY_ACTION"/>
</intent-filter>
My app wants to bundle multiple push notifications in one icon in the status bar.
When clicking on the icon, the multiple notifications should be received by the app to show them in listview mode.
There are already some entries in stackoverflow which come close to what I want to obtain and it did give me a better insight in handling pending intents and notification flags but they didn´t solve completely my problem.
First step: Creating the notification:
Following some entries in stackoverflow, I made the following assumptions:
One notification ID (notifyID) to obtain only one icon in status bar
A unique requestId parameter in the pending intent to differentiate between the various notifications requests within the same notification ID
FLAG_ACTIVITY_NEW_TASK used in notification intent and FLAG_UPDATE_CURRENT used in pending intent
Notification notification;
int icon = R.drawable.ic_launcher;
int smallIcon = R.drawable.ic_launcher;
int notifyID = 1;
long when = System.currentTimeMillis();
int requestID = (int) System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, NewActivity.class);
notificationIntent.putExtra("new_message", message);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int numMessages = 1;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setNumber(numMessages)
.setSmallIcon(smallIcon)
.setAutoCancel(true)
.setContentTitle("You have " +numMessages+ " new messages.")
.setContentText(message)
.setWhen(when)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
notificationManager.notify(notifyID, mBuilder.build());
The way I see it, each time a notification is sent by GCM, my app generates a notification to send to the notification manager taking into account the previous assumptions.
First problem: if I want to notify the user with the number of pending notifcations left, how can I get track of the previous number of sent notifications? Do I have to store it in storage media?
Second step: Tapping the notification icon in status bar containing multiple notifications:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showNotifications();
}
public void onResume() {
showNotifications();
super.onResume();
}
public void showNotifications() {
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().getString("new_message") != null) {
String newMessage = getIntent().getExtras().getString("new_message");
if (!newMessage.equals("")) {
handleMessage(newMessage);
getIntent().removeExtra("new_message);
}
}
}
}
public void onNewIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
if (intent.getExtras().getString("new_message") != null) {
String newMessage = intent.getExtras().getString("new_message");
if (!newMessage.equals("")) {
intent.removeExtra("new_message"); }
}
}
}
}
Second problem: I only receive the last notification sent. It seems to be that differentiating the pending intents with requestId didn´t do the trick. Also I thought that the different pending intents related to one notification icon would be handled by onNewIntent...
A possible solution that I was thinking about is to save incoming notifications from GCM in storage and get them on tapping the status bar icon, but for sure this cannot be the way Google meant it to be…
¿Any help?
for second step try this: PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);