How to handle Notification Touch event launch Activity using BroadcastReceiver - android

I have used broadcast receiver and alarm manager. Added the notification in particular date and time. The notification is showing fine. But when the user is touching the notification i want to launch myApplication.
Notification.Builder notification= new Notification.Builder(this);
notification.setContentTitle("MY Title");
notification.setContentText("Today you have scheduled for...");
notification.setSmallIcon(R.drawable.ic_app_launcher);
notification.setAutoCancel(true);
notification.build();
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = dateSpecified.getTime(); //Some future date like 20 feb 2015
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
NotificationPublisher class -BroadcastReciver
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
I referred this link.
I hope your understand what i'm trying to say.
Please anybody help me. Thanks lot.

But when the user is touching the notification i want to launch
myApplication.
Because NotificationPublisher BroadcastReceiver fire when notification is clicked so start Application from onReceive method of Receiver:
public void onReceive(Context context, Intent intent) {
// start application here
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intentn = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intentn);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notification);
}

Related

Notification Missing From Intent on Android 7.0

I have an alarm set up to deliver an intent with a notification to a broadcast receiver which then fires the notification. Pre 7.0, the notification is present in the intent when received, on 7.0 it's missing.
Here's the code which generates the notification.
public static void scheduleNotification(Context context, String message, long delay,
MainDisplay.NotificationType type) {
Notification.Builder builder = new Notification.Builder(context).setSmallIcon(
R.drawable.ic_stat_o)
.setContentTitle(
"Title")
.setContentText(
message)
.setStyle(
new Notification
.BigTextStyle()
.bigText(
message));
final Intent notificationIntent = generateNotificationIntent(context);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, builder.build());
notificationIntent.putExtra(TYPE_KEY, type);
final PendingIntent pendingIntent = generatePendingIntent(context, notificationIntent);
final long futureInMillis = SystemClock.elapsedRealtime() + delay;
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Here's the pending intent code.
public static PendingIntent generatePendingIntent(Context context, Intent notificationIntent) {
return PendingIntent.getBroadcast(context, 0, notificationIntent,
PendingIntent
.FLAG_UPDATE_CURRENT);
}
Here's the code that receives it.
public void onReceive(final Context context, Intent intent) {
final NotificationManager
notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
final Notification notification = intent.getParcelableExtra(NOTIFICATION);
final int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
Any ideas? Thanks!
I noticed that a serialized enum that I sent along was missing as well, I know there were changes in 7.0 with regards to intent transactions that were too large, but I'm not sure how that would apply here as no exceptions were thrown. I opted to simply send along the required info to construct the notification in onReceive.

Status bar notification auto starts activity

I am trying to do scheduled notification. All works except: When application is active and minimized. Notification auto starts activity without waiting for user to click on it.
On reveive:
public void onReceive(Context context, Intent paramIntent) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Notification notification = new Notification(R.drawable.logo_f, context.getResources().getString(R.string.notification_text), System.currentTimeMillis());
Intent notificationIntent = new Intent(context, TimeLeftActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, context.getResources().getString(R.string.notification_text), "", intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound=alarmSound;
// Fire the notification
notificationManager.notify(1, notification);
}
My notification start method:
private void createScheduledNotification(int sec)
{
// Get new calendar object and set the date to now
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Add defined amount of days to the date
calendar.add(Calendar.SECOND, sec);
// Retrieve alarm manager from the system
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
// Every scheduled intent needs a different ID, else it is just executed once
int id = 1;
// Prepare the intent which should be launched at the date
Intent intent = new Intent(this, TimeAlarm.class);
// Prepare the pending intent
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
// Register the alert in the system. You have the option to define if the device has to wake up on the alert or not
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
EDIT after Kirill answer. Error still persist. Notification auto starts pending intent and does not wait for click.
#Override
public void onReceive(Context context, Intent paramIntent) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent notificationIntent = new Intent(context, TimeLeftActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(context.getResources().getString(R.string.notification_text))
.setContentIntent(intent)
.setSound(alarmSound)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Fire the notification
notificationManager.notify(1, notification);
}
It is hard to find error, because you use deprecated API in your code, you should to use Notication.Builder
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
If you need to support old versions you can use NotificationCompat
UPDATE
This is sample from my app, it throws a notification, which open activity by click, I marked method to add intent.
String message = context.getString(R.string.notif_message);
Intent notificationIntent = new Intent(AddBpRecordActivity.ADD_ACTION);
NotificationCompat.Builder nb = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notif_logo)
.setContentTitle(message)
.setContentText(billet.comment)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
>>> .setContentIntent(PendingIntent.getActivity(context, (int) billet.id, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT))
.setWhen(System.currentTimeMillis());
Notification notification = nb.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) billet.id, notification);

Alarm and notification

I found this example of an alarm notification and I would just like to ask you to change two things.
This is MainActivity:
public void setRepeatingAlarm() {
Intent intent = new Intent(this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(129600000), pendingIntent);
}
And this is MyAlarmService:
public class MyAlarmService extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Locali Torino";
CharSequence message = "Visita le serate!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.disco,
"Visita le serate!", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}
In this way, when I launch my app, now I see the notification but I would like to see it do so only after "x" milliseconds.
And then I want to know how to launch the MainActivity clicking on the notification.
Thank you.
Call setRepeatingAlarm() with some delay. From service or from activity use e.g. Handler and post a runnable to it with small delay. If you are in activity, dont't forget to remove post action within your lifecycle methods, e.g. onStop(). If you want to make some action when user click on notification, edit contentIntent in your MyAlarmService.
E.g.
Intent action = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
action, 0);

updating notification in android every half n hour

I have the code for showing the notification in the status bar. I know the updating can be done by calling setLatestEventInfo() again, but I want the updating to be done in every half an hour.
How do I keep track of the time?
Does somebody know any function for that?
I even thought of using counter which keeps getting incremented every half an hour but again retrieving the time is a problem.
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.index1;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence notificationTitle = "My notification";
CharSequence notificationText = "Hello World!";
Intent notificationIntent = new Intent(this, NotificationAppActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, notificationTitle, notificationText, contentIntent);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
You have to use AlarmManager and schedule recurring event every 30 minutes. Then you need to handle this event and in broadcast receiver's onReceive() update your notification, but usually sending Intent to your service to do the job.
Example code:
Intent intent = new Intent(this, MyAlarmBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
long recurring = (30 * 60000); // in milliseconds
am.setRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), recurring, sender);
and your MyAlarmBroadcastReceiver is regular BroadcastReceiver with code in onReceive(). I prefer to use one broadcast receiver so I also add some additional data to the intent so my broadcast receiver knows what it should do, but you can have it separated if you like.
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive( Context context, Intent intent ) {
// ... do what you need to do here...
}
}
Use alarmManager as in example bellow:
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

Android reminder!

I would like to ask which service and how to use to make reminder in android... Let's say: after 10 minutes from now show me notification in notification bar...
Thanks for your answer
Obviously you should use AlarmManager in order to setup something to be executed in given PERIOD.
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), PERIOD, pi);
where the PERIOD is your time to something that should be executed in OnAlarmReceiver.
And then, just implement method in
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager nm = (NotificationManager);
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.tickerText = "10 Minutes past";
nm.notify(0, notification);
}
Enjoy.
You should use AlarmManager. With it you can schedule an intent to be delivered. Create a BroadcastReceiver to get it and show the notification.
Somethink like this i guess, you start an runnable after 10min and open an notification in the runnable's code.
Runnable reminder = new Runnable()
{
public void run()
{
int NOTIFICATION_ID = 1324;
NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.icon, "message", System.currentTimeMillis());
// Add and AUTO_CANCEL flag to the notification,
// this automatically removes the notification when the user presses it
note.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, ActivityToOpen.class), 0);
note.setLatestEventInfo(this, "message", title, i);
notifManager.notify(NOTIFICATION_ID, note);
}
};
Handler handler = new Handler();
handler.postDelayed(reminder, 600000);

Categories

Resources