This question already has an answer here:
How to write a notification that does absolutly nothing when clicked?
(1 answer)
Closed 2 years ago.
Is it possible to prohibit opening an activity with the notification by the FCM server?
I'm talking about the notification sent via the manifest
If the user clicks the notification, by default it open MainActivity.
I just want it to disappear and not open any activity
I try this but not work :
// [START handle_data_extras]
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d("TAG", "Key: " + key + " Value: " + value);
if (value.equals(myValue)) {
Toast.makeText(this, "Close", Toast.LENGTH_SHORT).show();
finish();
}
}
Temporary solution :
open an activity that closes all :
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d("TAG", "Key: " + key + " Value: " + value);
if (value.equals(myvaluefirebase)) {
Log.d("TAG", "Key value it's OK");
Intent mainIntent = new Intent(SplashActivity.this, **Close.class)**;
startActivity(mainIntent);
SplashActivity.this.finish();
finish();
}
}}
Set the pending intent like that
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
builder.setContentIntent(pendingIntent);
Also enable setAutoCancel()
builder.setAutoCancel(true);
Related
I am currently trying to send a local notification with an action. The action will push a string to the activity when selected. Unfortunately, when I try to pass a String I am unable to receive it on the activity, I have multiple log statements with different objects to see if maybe the system is recognizing it as something else but no luck. Event when I tried to send it in as a bundle, the bundle is sent but not the string! if I pass an int it works great! Any help would be appreciated, and yes I have been digging around for this and tried multiple solutions.
Code:
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setAction("action");
intent.putExtra("idforaction", 12345);
//intent.putExtra("test", "test message");
Bundle bundle = new Bundle();
bundle.putString("othertest","test message 2");
intent.putExtra("test", bundle);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MainActivity:
int notificationNum = getIntent().getIntExtra(idfoaction, -1);
Log.e(TAG, "get Extras " + notificationNum);
Log.e(TAG, "STRING? " + getIntent().getStringExtra("test"));
Log.e(TAG, "CHARSEQ? " + getIntent().getCharSequenceExtra("test"));
Log.e(TAG, "CHARS?" + (getIntent().getCharArrayExtra("test") != null ? getIntent().getCharArrayExtra("test").length + "" : "null"));
Log.e(TAG, "PARCELABLE?" + (getIntent().getParcelableExtra("test") != null ? getIntent().getParcelableExtra("test").toString(): "null"));
Log.e(TAG, "BUNDLE?" + (getIntent().getBundleExtra("test") != null ? "not null" : "null"));
Log.e(TAG, "BUNDLE?" + (getIntent().getExtras() != null ? "not null" : "null"));
if (getIntent().getExtras() != null) {
Log.e(TAG, "bundle " + getIntent().getExtras().getString("othertest", ""));
Log.e(TAG, "bundle " + getIntent().getExtras().get("othertest"));
}
Try this:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("my_key", "my_key_value");
And read:
Intent intent = getIntent()
String myValue = intent.getStringExtra("my_key"); // "my_key_value"
#Override
public void onMessageReceived(String from, Bundle data) {
dbhelper = DatabaseHelper.getInstance(this);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/teta")) {
if (message != null) {
final Alert alert = new Gson().fromJson(message, Alert.class);
Log.d(TAG, alert.getDesc() + " " + alert.getLink() + " " + alert.getTimeStamp() + " " + alert.getTitle());
dbhelper.addAlertsToDB(alert, DatabaseHelper.NEW);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(AppPreferences.NEW_ALERT_RECIEVED));
boolean notifPref = sharedPreferences.getBoolean(AppPreferences.PREFERENCE_RECIEVE_NOTIFICATION, false);
if (notifPref) {
sendNotification("You Have A New Job Notification.", alert.getTitle());
Log.d(TAG, "Notifications turned " + notifPref + " ...User will be notified");
} else {
Log.d(TAG, "Notifications turned " + notifPref);
}
}
}
}
private void sendNotification(String message, String title) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_notifications_active_white_24dp)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(message)
.setSubText(title)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(notificationBuilder);
//Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String strRingtonePreference = sharedPreferences.getString(AppPreferences.PREFERENCE_SOUND, "");
Uri defaultSoundUri = Uri.parse(strRingtonePreference);
notificationBuilder.setSound(defaultSoundUri);
boolean vibrate = sharedPreferences.getBoolean(AppPreferences.PREFERENCE_VIBRATE, false);
if (vibrate) {
long[] pattern = {0, 200};
notificationBuilder.setVibrate(pattern);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
So my problem is to notify user about new messages without annoying him if the user has not already checked the old notification in status bar. I am not able to persist notification id and notification builder.
My server sends new alerts in a continuous stream of 5-10 alerts at once, but each item arrives separately asynchronously often one after other with a split second difference.
So it becomes very annoying for the user since he has not dismissed/viewed the old one.
I wish to update the content of previous notification in the status bar without notifying user....just like Gmail does.
First, add an ID to each notification. It can be a hashcode of the message title for example.
Second, each time you want to post a notification, use 'getActiveNotifications()' to get the array of active notifications. And if you find one with an equal ID, update it passing the existing ID.
And, if you don't want the sound, vibration and ticker to be played again, use the 'setOnlyAlertOnce(true)' option.
I am working with GCM, and this is my onMessage function:
#Override
protected void onMessage(Context context, Intent intent) {
if (intent != null && intent.getExtras() != null) {
try {
String message = intent.getExtras().getString("message");
String userId = intent.getExtras().getString("user_id");
Log.i("","postda user id is:" + userId);
Log.i("","will enter here FRIENDS: ");
generateNotification(context, message, userId);
} catch (Exception e) {
Utils.appendLog("onMessage errror : " + e.getMessage());
Log.i(TAG, e.getMessage(), e);
}
}
}
This is my CreateNotification function:
private static void generateNotification(Context context, String message, String userID) {
Log.i("", "postda user message " + message + ".... userid: " + userID);
String title = context.getString(R.string.passenger_name);
Intent notificationIntent = new Intent(context, PSProfileActivity.class);
notificationIntent.putExtra("id", userID);
Log.i("", "postda ---------- userid: "+ userID);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Log.i("", "postda message: " + message + "....userID " + userID );
PSLocationCenter.getInstance().pref.setDataChanged(context, true);
PSLocationCenter.getInstance().pref.setDataChangedProfile(context, true);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(title).setContentText(message).setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentIntent(intent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
playTone(context);
}
And this is the PSProfileActivity onCreate function:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.inject(this);
mHeader = new ProfileHeader(this, backFromHeader);
mData = new ProfileData(this);
mButtons = new ProfileViewPagerButtons(PSProfileActivity.this, firstPage);
Bundle bundle = getIntent().getExtras();
if(bundle != null) id = bundle.getString("id");
Log.i("", "postda in profile id is:" + id);
if(!id.contentEquals(String.valueOf(PSLocationCenter.getInstance().pref.getUserId(PSProfileActivity.this)))){
findViewById(R.id.action_settings).setVisibility(View.INVISIBLE);
}
Log.i("", "postda in profile id is 2:" + id);
}
And this is my Logcat response:
04-17 15:33:53.650 9699-11695/nl.hgrams.passenger I/﹕ postda user id is:23
04-17 15:33:53.651 9699-11695/nl.hgrams.passenger I/﹕ postda user message alin reddd accepted your friend request..... userid: 23
04-17 15:33:53.651 9699-11695/nl.hgrams.passenger I/﹕ postda ---------- userid: 23
04-17 15:33:53.652 9699-11695/nl.hgrams.passenger I/﹕ postda message: alin reddd accepted your friend request.....userID 23
04-17 15:33:58.812 9699-9699/nl.hgrams.passenger I/﹕ postda in profile id is:28
04-17 15:33:58.814 9699-9699/nl.hgrams.passenger I/﹕ postda in profile id is 2:28
As you can see, I'm sending via the bundle an ID, but the one that I get on the other page, is a totally different id (it's actually the last ID that should have been gotten here). This is really weird, does anyone know why this is happening?
Use unique identitier in the PendingIntent:
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent.getActivity(context, iUniqueId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You are generating intent with the same id always. You need to pass the unique identifier as the second parameter and also need to add the Flag FLAG_UPDATE_CURRENT so that the extras get updated and you always get the latest extras that you passed .
So you have to generate intent like this :
PendingIntent intent = PendingIntent.getActivity(context, identifier , notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );
identifier can be anything unique like auto increment variable or current timestamp
The problem may be that you are only using extras to modify the PendingIntent. Try embedding the id in the data field of notificationIntent instead.
From http://developer.android.com/reference/android/app/PendingIntent.html
A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen. The parts of the Intent that are used for matching are the same ones defined by Intent.filterEquals. If you use two Intent objects that are equivalent as per Intent.filterEquals, then you will get the same PendingIntent for both of them.
I think you have to use this flag, FLAG_UPDATE_CURRENT.
Like this:
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
This would refresh the old intents with the new extras that you are passing via bundle and get correct data that matches the ID.
I have an application that request DownloadManager to start a download.
What I want to do is launch my app when user clicks on the download notification for the download that my app requested from DownloadManager. Below is the code in BroadcastReceiver for DownloadManager broadcasts.
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action))
{
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
long dlRef = getDlRef();
if (downloadId != dlRef) {
Log.d(Constants.TAG, "MY_DL_ID: " + dlRef + " EVENT FOR: " + downloadId);
} else {
Log.d(Constants.TAG, "Starting my activity");
Intent i = new Intent(context, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
How can I do that? In above code I get downloadId as 0.
Thanks,
Vinay
You want to be using:
intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)
which returns an long array.
After starting the download you can simply start your application as: Intent launchint = getPackageManager().getLaunchIntentForPackage("com.package.yourapp");
startActivity(launchint );
I am trying to use the BroadcastReceiver to receive a push notification containing only text, and it seems that it's simultaneously generating two notifications: one that is only the text I'm pushing, and one that includes all of the formatting and styles I've included in my NotificationCompat.Builder object. I know it's something inherent in how BroadcastReceiver is coded, because I've commented out the entire body of my onReceive() method and it still generates that basic notification. Is there a way to suppress that basic notification so it only sends the notification that I'm manually building?
Here's my code:
public class MyCustomReceiver extends BroadcastReceiver {
private static final String TAG = "MyCustomReceiver";
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
String channel = intent.getExtras().getString("");
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
Log.d(TAG, "got action " + action + " on channel " + channel + " with:");
Iterator itr = json.keys();
while (itr.hasNext()) {
String key = (String) itr.next();
Log.d(TAG, "..." + key + " => " + json.getString(key));
if (key.equals("alert"))
{
//Save the message to the globalDataString
SplashActivity.globalDataString.push(json.getString(key).toString());
SplashActivity.notificationFlag = true;
//call the method that generates and sends the notification I want
receiveNotification();
return;
}
}
}
catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
}
Any suggestions would be appreciated. Thanks!
*EDIT: Here is the code for my receiveNotification() class:
public void receiveNotification() {
NotificationCompat.BigTextStyle bts = new NotificationCompat.BigTextStyle();
bts.bigText(SplashActivity.globalDataString);
bts.setSummaryText("Tap to open app, swipe to dismiss message");
NotificationCompat.Builder m = new NotificationCompat.Builder(this);
m.setContentTitle("New Push Notification")
.setContentText(SplashActivity.globalDataString)
.setSmallIcon(R.drawable.app_icon)
.setStyle(bts);
Intent openApp = new Intent(this, MenuActivity.class);
// This ensures that navigating backward from the Activity leads out of
// the application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MenuActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(openApp);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
m.setContentIntent(resultPendingIntent);
Notification noti = m.build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(pushMessageID, noti);
pushMessageID++;
//reset notification
flag1 = false;
}