I want to start a foreground notification from a service.Here is my code:
Manifest :
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
Broadcast Receiver :
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "Charger connected (#)", Toast.LENGTH_SHORT).show();
Intent startIntent = new Intent(context, NotificationService.class);
startIntent.setAction("a_abhi_apps.batterychargenotifier.action.startforeground");
context.startService(startIntent);
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
Toast.makeText(context, "Charger disconnected (#)", Toast.LENGTH_SHORT).show();
stopIntent.setAction("a_abhi_apps.batterychargenotifier.action.stopforeground");
}
}
NotificationService.java :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.startforeground")) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Charging ")
.setContentText("Phone is charging");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// manager.notify(0, builder.build());
startForeground(0, builder.build());
} else if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.stopforeground")) {
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
I have declared broadcast receiver in manifest as it receives power state changed.So there is no related code in MainActivity.
I have commented this line in NotificationService.java :
manager.notify(0, builder.build());
I get notification if i remove the comment.But i would like to make it stick to the notification space,so that i can use that service to perform some other actions.
But i am unable to make it as a foreground notification.
You have to change your notification id in startForeground(0, builder.build()).
You can't use 0 as your notification id.
From here:
The identifier for this notification as per NotificationManager.notify(int, Notification); must not be 0.
Try this
mNotificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder note = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.name))
.setSmallIcon(R.drawable.quantum_ic_refresh_white_24);
note.setOnlyAlertOnce(true);
note.setOngoing(true);
note.setWhen( System.currentTimeMillis() );
note.setAutoCancel(false);
note.setContentText(getString(R.string.downloading_new_teachkits));
Notification notification = note.build();
mNotificationManager.notify(notifyID, notification );
You can follow below Code :-
private static int notification_id=1001;
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher3)
.setContentTitle(title)
.setContentText(DeviceName)
.setSubText(timestamp)
.setVisibility(visibility)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(vibrate)
.setOngoing(true)
.setFullScreenIntent(null, true);
Intent resultIntent = new Intent(this, NotificationActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManagerCompat mNotificationManager = (NotificationManagerCompat) NotificationManagerCompat.from(this);
Notification notification = mBuilder.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(notification_id, notification);
startForeground (notification_id, notification)
notification_id = notification_id + 1;
Related
Okay so what I am doing right now is getting a push notification through FCM that's been going well. Now I'm able to change the activity when application is on foreground, but how do I change it when I tap the notification in notification panel? Need help.
My Code:
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.mipmap.ic_launcher;
// on click activity for the notification !!!!!!!!!!
intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(mContext, TestActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long notificatioId = System.currentTimeMillis();
Intent intent = new Intent(getApplicationContext(), TestActivity.class); // Here pass your activity where you want to redirect.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, 0);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
currentapiVersion = R.mipmap.ic_notification_lolipop;
} else{
currentapiVersion = R.mipmap.ic_launcher;
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(currentapiVersion)
.setContentTitle(this.getResources().getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
.setContentIntent(contentIntent);
mNotificationManager.notify((int) notificatioId, notificationBuilder.build());
}
I have used in this manner to start a specific activity:
FireBaseMessagingService.java
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//The message will contain the Push Message
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");
//title for the notification.
String title = remoteMessage.getData().get("title");
//action string to perform the action e.g. open activity
String action = remoteMessage.getData().get("click_action");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);
//method for functioning the notification --->
sendNotification(message, title, bitmap, action);
}
private void sendNotification(String messageBody, String title, Bitmap image, String action) {
Intent intent = new Intent(this, SpecificActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("title", title);
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intent.putExtra("img", image);
intent.putExtra("msg", messageBody);
intent.putExtra("click_action", action);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this, "Default")
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.mipmap.app_icon)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_HIGH)
.setChannelId("Default")
.setVibrate(new long[]{1000, 1000})
.setContentIntent(pendingIntent);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
After this Add the following lines in the specificActivity.java part in the AndroidManifest.xml file:
<activity
android:name=".SpecificActivity">
<intent-filter>
<action android:name="OPEN_ACTIVITY" />
<!-- Add this OPEN_ACTIVITY string into your data payload while sending the notification from server side. -->
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
After this get the intent in the specific activity you are starting i.e. SpecificActivity.java file's onCreate() method.
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet())
{
String value = getIntent().getExtras().getString(key);
if (key.equals("click_action")) {
//perform the action you want to do with the key.
}
After adding these you are good to check the notifications from your mobile end.
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(mContext,ACTIVITY_TO_BE_DISPLAYED.class); // Replace ACTIVITY_TO_BE_DISPLAYED to Activity to which you wanna show
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
.setAutoCancel(true)
.setTicker("YOUR_TICKER_MSG")
.setSmallIcon(R.drawable.ic_notification_icon)
.setLargeIcon(icon)
.setContentTitle("YOUR_TITLE")
.setContentText("YOUR_TEXT")
.setContentIntent(intent);
notificationManager.notify(10, builder.build());
<!-- MainActivity is the parent for ResultActivity -->
<activity
android:name=".ResultActivity"
/>
Dont forget to adjust Manifest with child activity declaration
Pass your Activity you want to open when clicked into Intent.
Intent notificationIntent = new Intent(context, XYZActivity.class);
complete code:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, XYZActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
I want it to create a pendingIntent notification after clicking on a button on the screen that says 'notify'. So when the user clicks on the notification it will dial a number like 021-1234567. How do I do this?
I have been searching online for help but I can't seem to find anything relating to this.
public void notifyPendingIntent(View view) {
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ 0211234567));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// Build notification
Notification notify = new Notification.Builder(this)
.setContentTitle("Make this call")
.setContentText("New call must be made to 021 123 4567")
.setTicker("New Alert")
.setContentIntent(pIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notify);
}
I have this so far, but when I hit the button, nothing happens.
I tried this and it now works. Thanks to everyone who tried to help.
public void notifyPendingIntent(View view) {
NotificationCompat.Builder myNotification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.my_notification_icon)
.setContentText("Calling 021-12345678")
.setContentTitle("Phone Call Notification");
Intent phoneCall = new Intent(Intent.ACTION_CALL);
phoneCall.setData(Uri.parse("tel:021-12345678"));
PendingIntent phoneCallIntent = PendingIntent.getActivity(this, 0, phoneCall, PendingIntent.FLAG_UPDATE_CURRENT);
myNotification.setContentIntent(phoneCallIntent);
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, myNotification.build());
}
<!-- NOTE! Your uses-permission must be outside the "application" tag
but within the "manifest" tag. -->
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this
public void call() {
Toast.makeText(this,"call",Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel: 0211234567"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, callIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
notificationBuilder.setStyle(inboxStyle);
inboxStyle.setBigContentTitle("sdjshfjnds");
inboxStyle.addLine("sdjjsdfn");
notificationBuilder.setStyle(inboxStyle);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int NOTIFICATION_ID = 100;
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
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")
I'm making a gcm application, and now I can receive the notification
But when I click the notification, it just open the app.
I need to open another activity instead of Mainactivity
is there any way to do this?
final Intent intent = new Intent(context, YourActivity.class);
intent.putExtra("key", "value");
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.set...;
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Please read this for detail about creating a Notification http://developer.android.com/guide/topics/ui/notifiers/notifications.html.
Depend on http://developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse, there are two general situations of starting Activity from your notification – Regular activity and Special activity.
Methods below are the example of start 2 type of Activity:
Regular activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = null;
ComponentName componentName = intent.getComponent();
if (componentName != null) {
// 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) <== This comment must be wrong!
stackBuilder.addParentStack(componentName);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
resultPendingIntent = stackBuilder.getPendingIntent(REQUEST_CODE_START_ACTIVITY, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
} else {
resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
}
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Usage :
Intent intent = new Intent(this, SignInActivity_.class);
sendNotification(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title, message, intent);
The manifest XML should look like this
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignInActivity_"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
Special activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Note:
Because I use setDefaults(DEFAULT_ALL), the vibrate permission is require <uses-permission android:name="android.permission.VIBRATE" />
Yes, it's possible. You must set the "exported" flag of the activity in the manifest.xml to true.
Hope it helps.
Use this:
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent=new Intent(context,YourActivity.class);
PendingIntent pending=PendingIntent.getActivity(context, 0, intent, 0);
Notification notification;
if (Build.VERSION.SDK_INT < 11) {
notification = new Notification(icon, "Title", when);
notification.setLatestEventInfo(
context,
"Title",
"Text",
pending);
} else {
notification = new Notification.Builder(context)
.setContentTitle("Title")
.setContentText(
"Text").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pending).setWhen(when).setAutoCancel(true)
.build();
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
nm.notify(0, notification);
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.