Make Notification cleared by user or once clicked - android

I have a service that may show a notification, the problem is once the notification is set, it doesn't clear neither when clicked, nor when swiped on. I am using the flag Notification.FLAG_AUTO_CANCEL but it doesn't seem to do anything..
private NotificationManager nm;
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
private final int NOTIFY_ID = 1;
private void showNotification(String date, String name) {
try{
CharSequence text = "You have new Event";
Notification notification = new Notification(R.drawable.small_icon, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, viewEvents.class).putExtra("date", date), 0);
notification.setLatestEventInfo(this, name, "Date: "+date, contentIntent);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.FLAG_AUTO_CANCEL;
nm.notify(NOTIFY_ID, notification);
}catch(Exception e){
Log.i("Notification",e.toString());
}
}
So what am I doing wrong?

Try using Notification.Builder or NotificationCompat.Builder instead of rolling the Notification manually.
Among other things, this would prevent the bug in your code, where you are applying FLAG_AUTO_CANCEL to defaults rather than flags.

Notification.FLAG_AUTO_CANCEL is commented out in your code.
But in case it isn't then flag Notification.DEFAULT_LIGHTS should be setted in notification.defaults not in notification.flags

I use this code to show/hide notifications:
private Handler handler = new Handler();
private Runnable task = new Runnable() {
#Override
public void run() {
NotificationManager manager = (NotificationManager) contesto.getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(contesto.getApplicationContext(), SearchHistory.class);
PendingIntent contentIntent = PendingIntent.getActivity(contesto.getApplicationContext(), 0, launchIntent, 0);
//Create notification with the time it was fired
NotificationCompat.Builder builder = new NotificationCompat.Builder(contesto);
builder.setSmallIcon(R.drawable.ic_launcher).setTicker("MESSAGE HERE!").setWhen(System.currentTimeMillis()).setAutoCancel(true).setDefaults(Notification.DEFAULT_SOUND).setContentTitle("TITLE").setContentText("MESSAGE").setContentIntent(contentIntent);
Notification note = builder.build();
manager.notify(100, note);
}
};
And to invoke just put:
handler.post(task);

Related

How to create notification inside an activity in android?

I have a task in which I have to show Notification for an incoming message inside an activity using BroadcastReceiver with the address and content on the SMS. Now I have to click in order to insert the values in sms in database. When the task is finished i want it to clear from the activity. Is it possible to create notification for incoming sms inside an Activity?
You can Try This no generate your own Notification.
#SuppressWarnings("deprecation")
private static void generateNotification(Context context) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, "New Contact Added",
when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent intent = PendingIntent.getActivity(context, iUniqueId,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, "New", intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(2, notification);
}

Onclick Event for Notification not working in Android

i'm sending one notification from background service. If i click on that notification its not calling to perticular activity for some times. (Few times only its calling ).
this is my code:
private void postNotification(String msg, int beaconID) {
if(!notifyMsg.equalsIgnoreCase(msg)){
notifyMsg = msg;
Log.e(TAG, "---------postNotification------- called");
notifyIntent = new Intent(this,
WelcomeHotel.class);
notifyIntent.putExtra("content", msg);
notifyIntent.putExtra("from_activity", ""+TAG);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
BeaconMyService.this, 0, /*new Intent[] { notifyIntent }*/ notifyIntent,
/*PendingIntent.FLAG_UPDATE_CURRENT*/0);
Notification notification = new Notification.Builder(
BeaconMyService.this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Monitoring Region").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.setLatestEventInfo(getApplicationContext(), "Monitoring Region", ""+msg, pendingIntent);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(0, notification);
}
}
setLastEventInfo()
This method was deprecated in API level 11. Use Notification.Builder instead.
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
should to
new Notification.Builder(BeaconMyService.this)
.setDefaults(Notification.DEFAULT_ALL)
...
If you use minApi - pre-Honeycomb, you should to change one string
//new Notification.Builder(BeaconMyService.this)
new NotificationCompat.Builder(BeaconMyService.this)

notification can't go current activity

In my notification, I want to start current activity when click in pending intent. In google, many ways found and I tried many times, it didn't work. here is my code,
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
String startTime = intent.getStringExtra("Strar_time");
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long when = System.currentTimeMillis(); // notification time
Notification notification = new Notification(R.drawable.ic_launcher, "reminder", when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= notification.FLAG_AUTO_CANCEL;
notification.vibrate = new long[]{100, 200, 100, 500};
notification.defaults = Notification.DEFAULT_ALL;
Intent notificationIntent = new Intent(this, Goo.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP/* | Intent.FLAG_ACTIVITY_SINGLE_TOP*/);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent , 0);
notification.setLatestEventInfo(getApplicationContext(), "It's about time", "Your time is "+startTime, contentIntent);
notification.contentIntent=contentIntent;
nm.notify(NOTIF_ID, notification);
NOTIF_ID++;
Log.i("NotiID",NOTIF_ID+"");
}
Try this function given below,
private static void generateNotification(Context context, String message) {
int icon = R.drawable.launch_icon;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = null;
notificationIntent = new Intent(context, Main.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
Only one working way I found so far is to make a dummy activity, start it and finish it in onRusume(). However this technique only bring application to front and do not start application when it is closed.
Then I used following workaround to bring application on front if it is alive in background otherwise start it.
Manifest:
<application>
.
.
.
<activity
android:name=".DummyActivity"
/>
.
.
</application>
In code:
public class DummyActivity{
public static boolean isAppAlive;
#Override
protected void onResume() {
// start application if it is not alive
if(!isAppAlive){
PackageManager pmi = getPackageManager();
Intent intent = pmi.getLaunchIntentForPackage(Your applications package name);
if (intent != null){
startActivity(intent);
}
}
finish();
}
In your main activity's onCreateMethod.
#Override
public void onCreate(Bundle savedInstanceState) {
DummyActivity.isAppAlive = true;
}
It is obvious that when your application is fully closed, isAppAlive will restore to its default value which is false. Thus application will be start.

Notification inbox style

I wanted to create something like an instant messaging application. How do I display multiple messages all in one notification? I can create a notification that appear when user receive a single notification. But when the user receive more than one message how can I update the notification with the previous message? Should I save the messages into a database and display it out if the user did not cancel the notification? Or is there any other way that I can handle this?
Below is my notification code.
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, "IMTest- A new event is created" , when);
Intent notificationIntent = new Intent(context, IM_Chat.class);
notificationIntent.putExtra("topicId", topicId);
notificationIntent.putExtra("sender", sender);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 1, notificationIntent, Intent.FLAG_ACTIVITY_MULTIPLE_TASK | PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, topicName, "A new event ["+eventName+"] is added in "+topicName, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.ledARGB |= 0xff0000ff;
notification.ledOffMS |= 1000;
notification.ledOnMS |= 300;
notificationManager.notify(CommunitiesappConstant.NOTIFICATION_ID, notification);
You can update notification using same id and builder
http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Updating
private NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
private mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Different Id's will show up as different notifications
private int mNotificationId = 1;
//Some things we only have to set the first time.
private boolean firstTime = true;
private updateNotification(String message, int progress) {
if (firstTime) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("My Notification")
.setOnlyAlertOnce(true);
firstTime = false;
}
mBuilder.setContentText(message)
.setProgress(100, progress, true);
mNotificationManager.notify(mNotificationId, mBuilder.build());
}

Notification Sound Stops on Click

I use the following code to add the notification, and in the notification I add two features, one is Sound and other is flashing light.
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.cutomnotification);
contentView.setTextViewText(R.id.textView1,"Custom");
notification.contentView = contentView;
Intent notificationIntent = new Intent(v.getContext(), MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(v.getContext(), 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
notification.sound=android.provider.Settings.System.DEFAULT_RINGTONE_URI;
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags=Notification.FLAG_INSISTENT|Notification.FLAG_SHOW_LIGHTS|Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(HELLO_ID, notification);
In this I also use the custom layout,
Now I have two questions,
1) The sound plays and it stops when user clicks on notification tab,but I want to continue the sound until user press any button on custom layout.
2) I add a button in custom layout now i can implement onClickListener() on it.
Add this code after notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND;
You can create the NotificationCompat.Builder object without using setSound(). This will create a notification without any sound.
notification = mBuilder
.setStyle(notiStyle)
.setSmallIcon(notificationIcon)
.setTicker(title)
.setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.build();

Categories

Resources