Sending a notification from a service in Android - android

I have a service running, and would like to send a notification. Too bad, the notification object requires a Context, like an Activity, and not a Service.
Do you know any way to by pass that ? I tried to create an Activity for each notification but it seems ugly, and I can't find a way to launch an Activity without any View.

Both Activity and Service actually extend Context so you can simply use this as your Context within your Service.
NotificationManager notificationManager =
(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);

This type of Notification is deprecated as seen from documents:
#java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }
public Notification(android.os.Parcel parcel) { /* compiled code */ }
#java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }
Better way
You can send a notification like this:
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.
So if your minimum target API level is 4+ (Android 1.6+) use this:
import android.support.v4.app.NotificationCompat;
-------------
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mylogo)
.setContentTitle("My Notification Title")
.setContentText("Something interesting happened");
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());

#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification()
{
NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0);
//set
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.cal_icon);
builder.setContentText("Contents");
builder.setContentTitle("title");
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
nm.notify((int)System.currentTimeMillis(),notification);
}

Well, I'm not sure if my solution is best practice. Using the NotificationBuilder my code looks like that:
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
Manifest:
<activity
android:name=".MainActivity"
android:launchMode="singleInstance"
</activity>
and here the Service:
<service
android:name=".services.ProtectionService"
android:launchMode="singleTask">
</service>
I don't know if there really is a singleTask at Service but this works properly at my application...

If none of these work, try getBaseContext(), instead of context or this.

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 can I catch the click on notification?

I need to call some methods after clicking the notification. My notification has a pendingIntent that opens a browser. But I also have to do some other things AFTER user clicks it. Oh, and I must admit that I get my notifications from GCM(push).
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlString));
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(mBitmap)
.setContentTitle(title)
.setDefaults(Notification.DEFAULT_ALL)
.setContentText(body)
.setAutoCancel(true);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification myNotification = notificationBuilder.build();
myNotification.setLatestEventInfo(getBaseContext(), title, body, pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(TAG, myNotification);
To handle the click on the notification itself (not an action) you need to specify a ContentIntent as following:
notificationBuilder.setContentIntent(PendingIntent.getActivity(
context,
0,
new Intent(context, YourActivity.class)
.putExtra("extra_something", something)
.setData(Uri.parse("pass an uri if needed")),
PendingIntent.FLAG_UPDATE_CURRENT
))
Hope it helps.

Android PUSH notifications with PendingIntent overriding previous

I have an application that receive PUSH notifications. When notification "not1" is received, it shows as usual using notification manager. But when "not2" is received, is not showing below "not1" but overriding it. I need show all notifications.
I thought that using different requestCode for PendingIntent will solve the problem, but not. I also tried with PendingIntent.FLAG_UPDATE_CURRENT flag and many others (including no flags). My code right now is like this:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = null;
Notification notification = null;
Intent notificationIntent = new Intent(context.getApplicationContext(), SplashActivity.class);
notificationIntent.putExtra("text", text);
notificationIntent.putExtra("url", url);
PendingIntent intent = PendingIntent.getActivity(context, requestID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder = setBuilderNormalNotification(builder, context, text, intent);
notification = new NotificationCompat.BigTextStyle(builder).bigText(text).build();
notificationManager.notify(0, notification);
Where function setBuilderNormalNotification is the next:
private static NotificationCompat.Builder setBuilderNormalNotification(NotificationCompat.Builder builder, Context context, String text, PendingIntent intent)
{
builder
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(getNotificationIcon())
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), getNotificationIcon()))
.setContentText(text)
.setContentIntent(intent)
.setWhen(0)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(true);
return builder;
}
What Am I doing wrong, please?
Thanks a lot.
In your code notificationManager.notify(0, notification); That 0 is the constant ID you are using, since it is always the same the notifications stack.

Notification auto cancel not working for Android lollipop

I want to auto cancel my notification when user clicks on notification. The following code works good in all the devices except Android lollipop device. In Lollipop device, notification goes only when user swipes it off.
#SuppressWarnings("deprecation")
public void sendNotification(int id){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test")
.setContentText("Jump to next screen")
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
resultIntent, 0);
//PendingIntent.FLAG_UPDATE_CURRENT
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// id, if there is a need to update the notification later on.
mNotificationManager.notify(id, mBuilder.build());
Log.v(TAG, "Notification ID value " + id);
//mNotificationManager.cancel(id);
}
What is missing in this code?
Looks good to me. My auto cancel still works on 5.0.2. Let me give you a portion of my code:
public static void notif(int id, String title, String text, Context context, Class activity) {
// get an instance of the NotificationManager service
if (mNotifyMgr == null)
mNotifyMgr = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, activity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.launcher)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(notifIntent);
mNotifyMgr.notify(id, mBuilder.build());
}
modify following:
setAutoCancel(true) -> setAutoCancel(false);
then on action activity do the following
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
if you want to set special condition you can set by
intent.putExtra("key", "value")

Removing notification after click

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.

Categories

Resources