Displaying app icon in notification bar - android

I am working on this app. what i want to do is display the icon of my activity in notification bar on a button click. i want it to stay there permanently until some other event is done. currently i dound this code but its giving a lot of errors, kindly tell me an easy way to do this:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(icon.isChecked()) {
CharSequence text = getText(R.string.local_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.ic_launcher, "Track Your Life", System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}
});

Simple code for create Notification with icon
Intent intentSetDefault = new Intent(mContext, ConversationListActivity.class);
PendingIntent piSetDeafult = PendingIntent.getActivity(mContext, 0, intentSetDefault,
PendingIntent.FLAG_UPDATE_CURRENT);
// create pending intent for action discard
Intent intentdiscard = new Intent(mContext, NotificationReceiver.class).setType(CODE_DISCARD);
PendingIntent piDiscard = PendingIntent.getBroadcast(mContext, 0, intentdiscard,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder mBuilder =
new Notification.Builder(mContext)
.setTicker(title)
.setSmallIcon(R.drawable.ic_stat_notify_incoming_msg)
.setContentTitle(title)
.setContentText(text)
.setLargeIcon(mAppBitmap)
.setContentInfo(Integer.toString(smsCount))
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(false);
mBuilder.setContentIntent(piSetDeafult);
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
mNotifyMgr.notify(NOTIFICATION_SET_DEFAULT, notification);

Related

Remove notification on clicking (Not a duplicate) [duplicate]

I just started working with notifications and now I'm trying to remove the notification and launch the app once the notification has been tapped in the notificationcenter.
I tried to work with the following code:
import android.app.NotificationManager;
public class ExpandNotification {
private int NOTIFICATION = 546;
private NotificationManager mNM;
public void onCreate() {
mNM.cancel(NOTIFICATION);
setContentView(R.layout.activity_on);
//Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
I think this code executes the other class when tapped?
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, ExpandNotification.class), 0);
However the notification doesn't go away, nor does the application launch.
But I'm able to swipe it to left or right to remove it but that's not what I want..
To get the same effect using Notification.Builder or NotificationCompat.Builder call setAutoCancel(true) on the Builder instance.
Use the flag Notification.FLAG_AUTO_CANCEL
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent);
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
and to launch the app:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Create a new intent which will be fired if you click on the notification
Intent intent = new Intent(context, App.class);
// Attach the intent to a pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, intent_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
This answer is too much late but specially i write following solution because notification constructor become deprecated so use notification using builder , like following :
**.setAutoCancel(true)** is used to remove notification on click
and entire notification is like follwoing :
private void makeNotification(String title,String msg){
Intent resultIntent = new Intent(this, MasterActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentIntent(resultPendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setAutoCancel(true)
.setContentText(msg);
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
Calling this method with title and message you get perfect notification.
You can directly add .setAutoCancel(true) this line into your code in order to remove notification on click.
This must be added in your builder variable.
Example:
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Notification")
.setContentText("Hello")
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Best & simple way is set builder.setAutoCancel(true) it's cancel your notification after clicking on notification. I hope this code help you.
Builder for notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
For open an activity on clicking notification
Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
Show bulder in notification
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());
Complete code for show a notification with icon, image, title, description, auto cancel and on click open an activity
public void ShowIntentNotification(View v)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());
}
For my it was that
.setPriority(Notification.PRIORITY_HIGH);
that was causing the notification to not clear after click... make sure you use:
.setPriority(Notification.PRIORITY_DEFAULT);
And .setAutoCancel(true) should work.

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

Resume application by clicking notification from a service

I successfully created an activity which starts a service which by turn shows a notification like this
public int onStartCommand(Intent intent, int flags, int startId){
String notificationText = "working"
myNotification = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("test")
.setContentText(notificationText)
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
//FOLLOWING TECHNIQUE IS DEPRECATED
/* PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
myNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); */
myNotification.flags |= Notification.FLAG_NO_CLEAR;
myNotification.flags = Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(1, myNotification);
return START_STICKY;
}
I know there are other questions related to this one BUT they all use setLatestEventInfo which is deprecated
And this is what I call from another activity:
protected void beginBackgroundSer(){
intentService = new Intent(this, Service.class);
intentService.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.startService(intentService);
}
So what I'd like is to resume the activity whenever I click the notification by non-deprecated methods. Thank you very much for your help.
You can create a notification by using the following steps.
Create a notification id for the future reference to update the notification by notification manager.
// Notification ID to allow for future updates
private static final int MY_NOTIFICATION_ID = 1;
Create the text elements for the notification.
// Notification Text Elements
private final CharSequence tickerText = "This is a Really, Really, Super Long Notification Message!";
private final CharSequence contentTitle = "Notification";
private final CharSequence contentText = "You've Been Notified!";
Define the notification Action elements i.e. when the user clicks on the view in the notification drawer what action happens? We use intents for handling this.
// Notification Action Elements
private Intent mNotificationIntent;
private PendingIntent mContentIntent;
You can also define sound and vibration for this notification.
// Notification Sound and Vibration on Arrival
private Uri soundURI = Uri
.parse("android.resource://com.examples.Notification.StatusBarWithCustomView/"
+ R.raw.alarm_rooster);
private long[] mVibratePattern = { 0, 200, 200, 300 };
Create the notification using the Notification.Builder class. Do this in your onCreate()
mNotificationIntent = new Intent(getApplicationContext(),
YourActivity.class);
mContentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Build the Notification
Notification.Builder notificationBuilder = new Notification.Builder(
getApplicationContext())
.setTicker(tickerText)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true)
.setContentIntent(mContentIntent)
.setSound(soundURI)
.setVibrate(mVibratePattern)
.setContent(mContentView);
// Pass the Notification to the NotificationManager:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
From the documentations
public NotificationCompat.Builder setContentIntent (PendingIntent intent) - Supply a PendingIntent to send when the notification is clicked. If you do not supply an intent, you can now add PendingIntents to individual views to be launched when clicked by calling RemoteViews.setOnClickPendingIntent(int,PendingIntent). Be sure to read Notification.contentIntent for how to correctly use this.
So you can use setContentIntent(PendingIntent intent) method something like
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
myNotification = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("test")
.setContentText(notificationText)
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(contentIntent) //added this new line
.build();
notificationManager.notify(1, myNotification);

Show custom dialog in an intentservice

i am creating an app which will receive GCM notifications and show them as a dialog. is there any way to implement code to show a dialog in Intent Service?
There are two ways according to me.
On Click of Notification, Open a dialog box or dialog activity of
requirement.
Use BigStyle Notification but it requires api level above 16
Open your Dialog
/**
* Issues a notification to inform the user that server has sent a message.
*/
private void generateNotification(Intent intent) {
int requestID = (int) System.currentTimeMillis(); // Some changes required to work on 4.4 kitkat
// Notification Builder
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title")
.setContentText("Content of notification")
.setLargeIcon(
BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher));
// set default Ringtone
mBuilder.setSound(RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setAutoCancel(true);
// open yopur dialog activity on Click of notification
notificationIntent = new Intent(this, DialogActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Getting data From GCM
if (intent.getExtras().getString("data") != null
// passing data to Dialog
notificationIntent.putExtra("data", your_string_data);
}
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Pending intent shouid be PendingIntent.FLAG_UPDATE_CURRENT for data
PendingIntent pIntent = PendingIntent.getActivity(this, requestID,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(sNotificationId++, mBuilder.build());
}
Big Style Notification
// know device version
public static final int build = Build.VERSION.SDK_INT;
if(build >= 16){
// Big style notifications
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification noti = new Notification();
// Call method and send required intent
noti = setBigTextStyleNotification(intent);
noti.defaults |= Notification.DEFAULT_LIGHTS;
noti.defaults |= Notification.DEFAULT_VIBRATE;
noti.defaults |= Notification.DEFAULT_SOUND;
noti.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
mNotificationManager.notify(1, noti);
}
/**
* Big Text Style Notification
*
* #return Notification
* #see CreateNotification
*/
private Notification setBigTextStyleNotification(Intent intent) {
Bitmap remote_picture = null;
// Get data from intent
String trip_date = intent.getExtras().getString("Data");
// Create the style object with BigTextStyle subclass.
NotificationCompat.BigTextStyle notiStyle = new NotificationCompat.BigTextStyle();
notiStyle.setBigContentTitle("Title");
notiStyle.setSummaryText("");// this contain text like Gmail notification
try {
remote_picture = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);// getting icon
} catch (Exception e) {
e.printStackTrace();
}
// Add the big text to the style.
CharSequence bigText = "you have confirmed a new trip."
+ "Add to Calendar";
notiStyle.bigText(bigText);
// Creates an explicit intent for an ResultActivity to receive.
Intent resultIntent = new Intent(this, DashboardActivity.class);
// This ensures that the back button follows the recommended convention
// for the back key.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
resultIntent.putExtra("data");
// Adds the back stack for the Intent (but not the Intent itself).
stackBuilder.addParentStack(SplashActivity.class);
// Adds the Intent that starts the Activity to the top of the stack.
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
.setLargeIcon(remote_picture)
.setContentIntent(resultPendingIntent)
.addAction(R.drawable.yes, "", resultPendingIntent) // setting yes or No images
.addAction(R.drawable.cancel, "", resultPendingIntent) //Cancel images
.setContentTitle("").setContentText("") //Title and Content
.setStyle(notiStyle).build();//Style of notifications
}
Check Google Docs on notifications:
Notifications
Notifying the User

when to clear notification count of status notification in android

I have a method for creating notification. I want to clear notification number as soon as a user clicks on status notification.
public void createNotification(){
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification=null;
notification = new Notification(R.drawable.ic_launcher, "You have a new message", System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.number = **count**++;
Intent intent = new Intent();
intent.setClass(TabInterfaceActivity.this, TabInterfaceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentIntent = activity;
notification.setLatestEventInfo(this, " New Message", message, notification.contentIntent);
}
If by "I want to clear notification number" you mean you want to keep the notification itself still displayed, but you want just to update/remove counter, then you should set your notification PendingIntent to point to your code that would handle this scenario for you, and when it completes it shall redirect to your target TabInterfaceActivity (or you can make it more flexible and pass target in PendingIntent's Bundle).

Categories

Resources