String parameters not sending to activity from local notification - android

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"

Related

FirebaseMessagingService Notification Server (must not open) [duplicate]

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);

Android: Cannot save and read all values in the Bundle

I have following method which is saving three values into intent which is appended to created alarm.
public static Boolean setUniqueAlarm(Long alarmId, String occurenceTime, Context context) {
Boolean saveResult = null;
try {
DateTime dt = TimeHelper.getDateTimeObject(occurenceTime);
Logger.d("Year: " + dt.getYear() + ", month: " + dt.getYear() + ", day: " + dt.getDayOfMonth() + ", hour: " + dt.getHourOfDay() + ", minute: " + dt.getMinuteOfHour());
Logger.d("Occurrence time to save: "+occurenceTime);
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
// Pass the intent type and other additional values into bundle
Bundle bundle = new Bundle();
bundle.putString(Constants.Global.ALARM_TYPE, Constants.Global.ALARM_TYPE_UNIQUE);
bundle.putString(Constants.Global.ALARM_OCCURRENCE_TIME, "123456");
bundle.putLong(Constants.Global.ALARM_UNIQUE_ID, alarmId);
alarmIntent.putExtras(bundle);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, dt.getMillis(), pendingAlarmIntent);
saveResult = true;
} catch (Exception e) {
Logger.e(e.getMessage());
saveResult = false;
}
return saveResult;
}
In receiver i have following code:
#Override
public void onReceive(Context context, Intent intent) {
try {
Logger.d("ALARM RECEIVED!!!");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
// Device battery life will be significantly affected by the use of this API.
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
// Acquire the lock
wl.acquire();
//Release the lock
wl.release();
// Get the intent type (or stored variables)
Bundle extras = intent.getExtras();
mAlarmType = extras.getString(Constants.Global.ALARM_TYPE);
mAlarmId = extras.getLong(Constants.Global.ALARM_UNIQUE_ID, 0);
mOccurenceTime = extras.getString(Constants.Global.ALARM_OCCURRENCE_TIME, "nothing");
triggerActionBasedOnTheAlarmType(mAlarmType, mAlarmId, mOccurenceTime, context);
} catch (Exception e) {
TrackingEventLogHelper.logException(e, Constants.Global.EXCEPTION,
Constants.ExceptionMessage.EXC_CANNOT_PROCESS_RECEIVED_ALARM, true);
}
}
Problem is that variable mOccurenceTime is always null, rsp. "nothing".
I tried to get values from intent and from Bundle but still without the success. Is not bundle count of items limited?
How can i get value mOccurenceTime in the right way?
Many thanks for any advice.
This is the right way to do it - specify a flag !
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Instead of the:
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, 0);
Because the 0 for the flags is what will cause you a headache
This is probably such a popular problem because Google's sample code neglected to include Extra's in an Alarm.
Solved here:
Android cannot pass intent extras though AlarmManager

NotificationCompat.Builder addAction - Boolean always true

I have the following code:
public void sendNewNotification (Booking updateBooking) {
String msg;
if (updateBooking.getJobStatus () == Booking.eeJob_OnRoute) {
msg = "Your driver has been dispatched.";
} else if (updateBooking.getJobStatus () == Booking.eeJob_POB) {
msg = "Your driver has arrived.";
} else if (updateBooking.getJobStatus () == Booking.eeJob_Complete) {
Variables.driverrated = false;
msg = "Your booking has been completed. Thank you for using " + Variables.setting.getCompanysName () + ".";
} else if (updateBooking.getJobStatus () == Booking.eeJob_NoShow) {
msg = "Unfortunately your driver was unable locate you. Please call the office on " + Variables.setting.getCompanytelephone () + ".";
} else if (updateBooking.getJobStatus () == Booking.eeJob_Cancelled) {
msg = "Your booking has been cancelled. Please call the office on " + Variables.setting.getCompanytelephone () + " if this is incorrect.";
} else {
return;
}
PendingIntent detailsIntent = PendingIntent.getActivity (this, 0, new Intent (this, HomeActivity.class)
.putExtra ("booking", updateBooking)
.putExtra ("track", false),
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent trackingIntent = PendingIntent.getActivity (this, 0, new Intent (this, HomeActivity.class)
.putExtra ("booking", updateBooking)
.putExtra ("track", true),
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder (this);
builder.setAutoCancel (true);
builder.setDefaults (Notification.DEFAULT_ALL);
builder.setWhen (System.currentTimeMillis ());
builder.setContentTitle (Variables.setting.getCompanysName () + " - booking update");
builder.setSmallIcon (R.drawable.notification);
builder.setTicker (Variables.setting.getCompanysName () + " - booking update");
builder.setPriority (NotificationCompat.PRIORITY_HIGH);
builder.setContentText (msg);
builder.setContentIntent (trackingIntent);
builder.addAction (R.drawable.documents_32px, "DETAILS", detailsIntent);
if (updateBooking.getJobStatus () != Booking.eeJob_Complete) {
builder.addAction (R.drawable.notification, "TRACK", trackingIntent);
} else {
builder.addAction (R.drawable.profile_32px, "RATE", detailsIntent);
}
NotificationManager manager = (NotificationManager) getSystemService (NOTIFICATION_SERVICE);
manager.notify (getTaskId (), builder.build ());
}
My issue is in my onCreate function I have these two lines:
m_updateBooking = (Booking) getIntent ().getSerializableExtra ("booking");
m_TrackDriver = (Boolean) getIntent ().getSerializableExtra ("track");
m_updateBooking works flawlessly. But m_TrackDriver is ALWAYS true. No matter what button I press. Can anyone explain why this is?
Thanks in advance for all your help.
Since your Intent has the same action for both the PendingIntent, you need to specify a different requestCode otherwise with FLAG_UPDATE_CURRENT the extras in the PendingIntent will be replaced by the new extras in the Intent. For this reason you have always true, because it is in the last PendingIntent requested.
This StackOveflow answer explains in details how PendingIntent works.
To resolve your issue change your code like this:
PendingIntent detailsIntent = PendingIntent.getActivity (this, 0, new Intent (this, HomeActivity.class)
.putExtra ("booking", updateBooking)
.putExtra ("track", false),
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent trackingIntent = PendingIntent.getActivity (this, 1, new Intent (this, HomeActivity.class)
.putExtra ("booking", updateBooking)
.putExtra ("track", true),
PendingIntent.FLAG_UPDATE_CURRENT);

Activity does not get correct bundle

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.

how to start an activity in handler

trying to trigger an Activity from a handler.
my other option is triggering from a broadcastReceiver.
this is what ive tried and it doesnt work.
public void handleMessage(Context context, Intent intent)
{
Log.v(tag,"handling message.........");
String messageString = intent.getExtras().getString("message");
C2DMMessage newC2DMMessage = new C2DMMessage(messageString);
Intent mIntent = new Intent(context,popad.class);
context.startActivity(mIntent);
String message_body = String.valueOf(newC2DMMessage.getParamValue("message_body"));
Toast.makeText(context, "message was recieved!!!!: '" + message_body + "'", Toast.LENGTH_LONG).show();
}
open to suggestions for a better way to start an activity.
Any errors you get in Logcat would be most helpful in your questions
Try changing :
Intent mIntent = new Intent(context,popad.class);
context.startActivity(mIntent);
To :
Intent mIntent = new Intent(context,popad.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);

Categories

Resources