Notification do nothing when clicked - android

So I would like to create a notification that, when clicked, will open my MainActivity and do something according to the extras I've put in the intent.
Right now, the notification works perfectly, but once I click it, nothing happens. I've search a little bit and have done some modification to my code :
I have added android:launchMode="singleTop" to my activity in the manifest.
I have put the code to execute in my MainActivity in the onNewIntent method :
#Override
protected void onNewIntent(Intent intent){
System.out.println("Entering onNewIntent!!!!!!!");
if(getIntent().getExtras() != null) {
url = getIntent().getExtras().getString("url");
System.out.println("URL in Main Activity : " + url);
if (url != null && url != "") {
saveFile(url);
dezipFile();
}
}
}
But nothing changed, I've put some System.out to see if it even reach the beginning of the onNewIntent... But nothing is shown on the console.
Here is the code where I create the notification :
private void createNotification () {
Intent downloadIntent = new Intent(getApplicationContext(), MainActivity.class);
downloadIntent.putExtra("url", url);
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent downloadPendingIntent = PendingIntent.getService(getApplicationContext(), 0, downloadIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "Notif")
.setSmallIcon(R.drawable.icon_notif)
.setContentTitle(getApplicationContext().getString(R.string.notif_title))
.setContentText(getApplicationContext().getString(R.string.notif_content))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(downloadPendingIntent)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notification_download", "Dowload BD infos", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
builder.setChannelId("notification_download");
}
NotificationManagerCompat notification = NotificationManagerCompat.from(getApplicationContext());
notification.notify(1, builder.build());
}
If anybody knows what I did wrong, it will be really appreciated!

Add this:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "Notif")
.setSmallIcon(R.drawable.icon_notif)
.setContentTitle(getApplicationContext().getString(R.string.notif_title))
.setContentText(getApplicationContext().getString(R.string.notif_content))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(downloadPendingIntent)
.setAutoCancel(true);
Intent mIntent = new Intent(context, YourActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(mIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);

You can set the activity launched when user clicks on a notification as follows:
Intent resultIntent = new Intent(this, targetActivityClass);
Intent backIntent = new Intent(this, backActivityClass);
Intent[] intentArray = new Intent[]{backIntent, resultIntent};
PendingIntent resultPendingIntent = PendingIntent.getActivities(this, 0, intentArray,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
builder.setContentIntent(resultPendingIntent);
This code also sets the activity launched when user clicks the back button after clicking the notification.

Related

Android - notification putExtra issue

I've searched for about hour to find some solution how to send extras to activity when user clicks in notification box but everything I've found didn't work for me.
I need to pass event ID to activity where I show user info about this event.
I've used setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), setAction("Action"), PendingIntent.FLAG_UPDATE_CURRENT and combination of all of these solution but neither didn't work.
That's my code:
Notification.Builder notiBuilder = new Notification.Builder(context);
notiBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
notiBuilder.setSmallIcon(R.drawable.logo);
notiBuilder.setContentTitle(context.getString(R.string.eventNitificationTitle));
notiBuilder.setContentText(obj.getString("nazwa") + " " + obj.getString("data"));
Intent eventIntenet = new Intent(context, EventActivity.class);
eventIntenet.setAction("Action_"+id);
eventIntenet.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
eventIntenet.putExtra("eventID", id);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, eventIntenet, PendingIntent.FLAG_UPDATE_CURRENT);
eventIntenet = null;
notiBuilder.setContentIntent(pIntent);
pIntent = null;
NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notiManager.notify(Integer.parseInt(id), notiBuilder.build());
} else {
notiManager.notify(Integer.parseInt(id), notiBuilder.getNotification());
}
And way to get my Int:
this.eventID = getIntent().getIntExtra("eventID", -1);
Everytime when I click in notification, I'm moving to activity but getExtra returns -1.
You can try something along these lines:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ChatService.this).setSmallIcon(R.drawable.app_icon)
.setContentTitle(senderName)
.setContentText("Notification Text Here");
mBuilder.setAutoCancel(true);
Intent resultIntent = new Intent(MyService.this, TargetActivity.class);
resultIntent.putExtra("eventID", id);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MyService.this);
stackBuilder.addParentStack(TargetActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, mBuilder.build());
If your app is already running and your EventActivity is already on the top of the stack, this code:
this.eventID = getIntent().getIntExtra("eventID", -1);
will always use the Intent that EventActivity was started with the first time.
You should override onNewIntent() and get the "extra" from the Intent that is passed as an argument to that method.

Android: clicking the foreground notification from a service doesn't show activity

edit: My code worked fine, I was simply giving it the wrong Activity class (multiple APK build project using shared library).
I'm using the following code to display a foreground notification for my Service. For some reason though, it doesn't show me my activity when I click on the notification.
I've checked out various StackOverflow posts and followed accordingly, and even the sample FakePlayer from CommonsWare but to no avail.
protected void updateNotification(String subtitle) {
// The PendingIntent to launch our activity if the user selects this notification
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Show notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_headset_mic)
.setWhen(System.currentTimeMillis())
.setContentTitle("AirWaves: " + G.SETTINGS.deviceName)
.setContentText(subtitle)
.setContentIntent(pendingIntent)
.setOngoing(true);
startForeground(NOTIFICATION_ID, builder.build());
}
Anyone have an idea where I might be going wrong with this?
i have also implement notification consider the following example
public void sendNotification(Context context,String message, String action) {
try {
int icon = R.drawable.notilogoboss;
String title = context.getString(R.string.app_name);
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("message", message);
intent.putExtra("action", action);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logoboss))
.setSmallIcon(icon)
.setContentTitle(title)
.setWhen(System.currentTimeMillis())
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int notId = UUID.randomUUID().hashCode();
notificationManager.notify(notId, notificationBuilder.build());
} catch (Exception e) {
}
}
Please try the following method to create the pending intent:
Intent intent = new Intent( context, MainActivity.class );
intent.putExtra( "message", message );
intent.putExtra("action", action);
TaskStackBuilder stackBuilder = TaskStackBuilder.create( context );
stackBuilder.addParentStack( MainActivity.class );
stackBuilder.addNextIntent( intent );
PendingIntent pendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT );
notificationBuilder.setContentIntent( pendingIntent );
Try changing the flag for the pending intent to this:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Also, what is the startForeground(NOTIFICATION_ID, builder.build()); method that you are using? can you post that as well for additional help?

Multiple notification in android for same app not working?

I have implemented push notifications for my android app .I am able to show multiple notification in notification bar but only one notification work at a time.If I click on any notification it will start the intended activity and that particular notification will disappear from notification bar but other notification for same app will become dead.Nothing happens when I click on rest of the notification.My code for handling notification is following:
private void sendNotification(String msg, String msgId, int notificationId,
int type) {
// SharedPreferences prefs = getSharedPreferences(
// Utility.PREFS_NAME, MODE_PRIVATE);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = null;
Bundle bundle = new Bundle();
if (type == 1) {
intent = new Intent(this, Activity_Received.class);
// bundle.putString("greeting", msg);
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
} else if (type == 2) {
intent = new Intent(this, Activity_Birth.class);
} else {
return;
}
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
intent.putExtras(bundle);
PendingIntent contentIntent;
// The stack builder object will contain an artificial back stack
// for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out
// of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
if (type == 1) {
stackBuilder.addParentStack(Activity_Received.class);
} else {
stackBuilder.addParentStack(Activity_Birth.class);
}
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
Please advise what do I need to change in above code so that I can click on every notification that I receive for my application and start the intended activity.
Pass a different notificationId for each different notification you want to have in the method: sendNotification(String msg, String msgId, int notificationId, int type)
I have wrote the following method which is working in case of multiple notifications.
private void pushNotification(String msg, String msgId, int notificationId,
int type) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Bundle bundle = new Bundle();
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
Intent intent = new Intent(this, Activity_ReceivedGreeting.class);
intent.putExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), notificationId, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
The key was to remove the FLAGS on pending intent.

How to ask Yes/No in notification and then launch the app and run corresponding method? Source code and screenshot attached

I have prepared a simple test app which posts a notification on a button click:
The source code from MainActivity.java creating the notification is displayed below:
Button showButton = (Button) findViewById(R.id.show);
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
appIntent.putExtra("my_data", 12345);
String question = getString(R.string.the_question);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(mContext)
.setContentTitle(question)
.setContentText(question)
.setTicker(question)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
mManager.notify(NOTIFY_ID, notification);
}
});
My question is: how to modify the notification, so that the user is asked a Yes/No question (in this case: "Do you want to open the car?") and - after she selects Yes or No to launch the same app and run a corresponding method in it (in this case: openCar() or closeCar() method).
I probably should use NotificationCompat.Action.Builder - but how exactly?
Also I am not really sure if this code is the correct code for launching an app from notification and what flags should I use:
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
And finally I wonder if hardcodidng some random number in NOTIFY_ID is the correct way when posting notifications?
Here is a source code I used for notification with Login/Register action.
private void sendNotification(String message, String title) {
try {
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_ONE_SHOT);
Intent secondActivityIntent = new Intent(this, SecondActivity.class);
PendingIntent secondActivityPendingIntent = PendingIntent.getActivity(this, 0 , secondActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Intent thirdActivityIntent = new Intent(this, ThridActivity.class);
PendingIntent thirdActivityPendingIntent = PendingIntent.getActivity(this, 0 , thirdActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_3d_rotation_white_36dp)
.setContentTitle(title)
.setContentText(message)
.addAction(R.drawable.ic_lock_open_cyan_600_24dp,"Login",secondActivityPendingIntent)
.addAction(R.drawable.ic_lock_pink_700_24dp,"Register",thirdActivityPendingIntent)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
To use it: simply call this method sendNotification(String yourMessage, String yourTitle)
e.g. sendNotification("Hello Message", "Hello Title")
Here is a snapshot of the output
Notify user on pending Intent.. an example is here..
public void notifyUser() {
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(HappyActivity.this, NotificationDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// use the flag FLAG_UPDATE_CURRENT to override any notification already
// there
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.ic_launcher,
"Question.....?????", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "title",
"Explanation of question..", pendingIntent);
// 10 is a random number I chose to act as the id for this notification
notificationManager.notify(10, notification);
}

Android: activity referesh when noification fire

Currrently I am working on Notification in andorid.
Here code is notification arrive....
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setTicker("New Task Here!!!");
if(taskdata.get(0).getDescription().equals(""))
{
int stringId = context.getApplicationInfo().labelRes;
String appname = context.getString(stringId);
mBuilder.setContentTitle(appname);
}
else
{
mBuilder.setContentTitle(taskdata.get(0).getDescription());
}
long l = Long.parseLong(taskdata.get(0).getDateTime());
Date date =new Date(l);
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a ");
String alarmtime = formatter.format(date);
String dateString= DateFormat.format("dd/MM/yyyy",date).toString();
mBuilder.setContentText(alarmtime+","+dateString);
Intent resultIntent = new Intent(context, TaskDetail.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
Bundle bundledata = new Bundle();
bundledata.putString("ImagePath", taskdata.get(0).getImagePath());
bundledata.putString("Des", taskdata.get(0).getDescription());
bundledata.putString("DateTime", FlagValue);
resultIntent.putExtras(bundledata);
stackBuilder.addParentStack(TaskDetail.class);
//ringtone on
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);
mBuilder.setAutoCancel(true);
// Adds the Intent that starts the Ac tivity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
// here this activity will refresh when fire the receive
Intent activityintent = new Intent(context,MainActivity.class);
PendingIntent contentintent = PendingIntent.getActivity(context, 0, activityintent, PendingIntent.FLAG_UPDATE_CURRENT);
activityintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activityintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
}
My issue is :
When Nofification come that time MyActivity.class Activity will be refresh.
I am also refer this link Android Refresh Activity from Notification but in my application not wok.
If you have Any Idea Please Help me.
Thank you in Advance.
Add the following function in the end of the notification function .
onCreate(null)

Categories

Resources