i need to show a notification in a method from intent service, i modify the context to "getApplicationContext" but it doesnt show anything.
Im using the android example: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
private void notf_SinConexion()
{
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder( getApplicationContext() )
.setSmallIcon( R.drawable.ic_action_action_alarm_on )
.setContentTitle( "Title" )
.setContentText( "Message" );
Intent resultIntent = new Intent( getApplicationContext(), MainActivity.class );
TaskStackBuilder stackBuilder = TaskStackBuilder.create( getApplicationContext() );
stackBuilder.addParentStack( MainActivity.class );
stackBuilder.addNextIntent( resultIntent );
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent( resultPendingIntent );
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService( Context.NOTIFICATION_SERVICE );
// mId allows you to update the notification later on.
mNotificationManager.notify( 10, mBuilder.build() );
}
First you need to read this article on how to use Notifications.
Next use this to send a Notification, you can write this code in the service class at the point where you receive some data from the client.
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
CharSequence notiText = "Your notification from the service";
long meow = System.currentTimeMillis();
Notification notification = new Notification(icon, notiText, meow);
Context context = getApplicationContext();
CharSequence contentTitle = "Your notification";
CharSequence contentText = "Some data has arrived!";
Intent notificationIntent = new Intent(this, YourActivityThatYouWantToLaunch.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
int SERVER_DATA_RECEIVED = 1;
notificationManager.notify(SERVER_DATA_RECEIVED, notification);
Related
I am trying to start an activity from a notification. Upon starting that activity, I add data via intent.putextra to the intent so the activity shows the right content for the situation.
The activity that is being started is supposed to be open only once in the stack. I did achieve this via
android:launchMode="singleTop"
in my manifest.
However - and now I come to my question - if this activity is already running, I want it to close and replace it with the instance I am creating with the specific additional data (put extra). How can I achieve this?
Heres the code of my notification:
public void newMessageNotification(String title, String message, String otherusernumber, String requestStatus, String sendername) {
notificationManager = NotificationManagerCompat.from(this);
Intent chatIntent = new Intent(this,ChatActivity.class);
//these three strings define the behaviour of the chat activtity
chatIntent.putExtra("otherUsername", sendername);
chatIntent.putExtra("otherUsernumber", otherusernumber);
chatIntent.putExtra("requestStatus", requestStatus);
chatIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), chatIntent,
PendingIntent.FLAG_UPDATE_CURRENT);;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_new_message)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(1, notification);
}
Try below code
Add PendingIntent in notification
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Full create notification code
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =
(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager . getDefaultUri (RingtoneManager.TYPE_NOTIFICATION);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String Ch_id = "yourappname_01";
// The user-visible name of the channel.
CharSequence name = "Notification";
// The user-visible description of the channel.
//String description = getString(R.string.channel_description);
int importance = NotificationManager . IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(Ch_id, name, importance);
mChannel.setSound(defaultSoundUri, new AudioAttributes . Builder ().build());
notificationManager.createNotificationChannel(mChannel);
// Create a notification and set the notification channel.
notification = new Notification . Builder (this, Ch_id)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setContentIntent(pendingIntent) //Add PendingIntent
.setChannelId(Ch_id)
.build();
} else {
// Create a notification
notification = new Notification . Builder (this)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent) //Add PendingIntent
.build();
}
//Generate Diff Notification
int m =(int)((new Date ().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notification);
Update
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_ONE_SHOT);
I hope this can help you!
Thank You.
Try to add flag: Intent.FLAG_ACTIVITY_NEW_TASK to your Intent
Try Below
Intent intent = new Intent(this, ActivityDestination.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ACTIVITY_NEW_TASK);
I faced an issue with Notification within BroadcastReceiver().
as I know, My code worked properly before but it doesn't work now.
sometimes NotificationTicker appear but no title and content has been appeared.
here is my code. my searches couldn't help me to find where is the problem.
here is my CODE:
private void MyNotification(Context context) {
String NotificqationText = "NotificqationText";
String NotificationTitle = "NotificationTitle ";
String NotificationTicker = "NotificationTicker";
PendingIntent MyPendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, Splash.class), 0);
NotificationCompat.Builder MyNB = new NotificationCompat.Builder(context);
MyNB.setSmallIcon(R.drawable.icon);
MyNB.setContentTitle(NotificationTitle);
MyNB.setContentText(NotificqationText);
MyNB.setTicker(NotificationTicker);
MyNB.setAutoCancel(true);
MyNB.setContentIntent(MyPendingIntent);
Bitmap MyPicture = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
MyNB.setLargeIcon(MyPicture);
NotificationCompat.BigPictureStyle MyPicStyle = new NotificationCompat.BigPictureStyle().bigPicture(MyPicture);
MyPicStyle.setSummaryText("Etude can makes our life Enlightened");
MyNB.setStyle(MyPicStyle);
MyNB.setStyle(new NotificationCompat.BigTextStyle());
NotificationCompat.BigTextStyle MyText = new NotificationCompat.BigTextStyle();
MyText.bigText(NotificqationText);
MyText.setBigContentTitle(NotificationTitle);
NotificationManager MyNotifyManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
MyNotifyManager.notify(1, MyNB.build());
}
I used Toast message to find my broadcastreceiver works or not and find broadcast works properly and only notification has problem
Try this code :
private void MyNotification(Context context) {
String NotificqationText = "NotificqationText";
String NotificationTitle = "NotificationTitle ";
String NotificationTicker = "NotificationTicker";
Intent intent = new Intent(this, Splash.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK));
PendingIntent MyPendingIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Bitmap MyPicture = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
Notification MyNB = new Notification.Builder(this)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(MyPicture)
.setStyle()
.setBigContentTitle(NotificationTitle)
.setContentTitle(NotificationTitle)
.setContentText(NotificqationText)
.setTicker(NotificationTicker)
.setAutoCancel(true)
.setContentIntent(MyPendingIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
MyNB.flags |= Notification.FLAG_SHOW_LIGHTS;
MyNB.flags |= Notification.FLAG_AUTO_CANCEL;
MyNB.defaults = Notification.DEFAULT_ALL;
notificationManager.notify((int)System.currentTimeMillis(), MyNB);
}
I'm implementing a notification service and I have problems to receive the messages in Android 2.3. I receive the messages in versions 4.0 and newer but not in 2.3. In logcat appears the following errors:
Could not find class 'com.google.android.gms.ads.internal.b.c', referenced from method com.google.android.gms.ads.internal.n.e.a
.
.
Could not find class 'android.app.Notification$Builder', referenced from method com.google.android.gms.common.l.a
What could be the problem? This is my method to send the notification:
private void sendNotification(String msg) {
MainActivity.notificationClicked = true;
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
String strMessage = loadPreferences();
String newMessage = "";
if (!strMessage.isEmpty())
newMessage = strMessage + "<br>" + msg;
else
newMessage = msg;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.text, Html.fromHtml(newMessage));
Notification notification = new Notification(icon, Html.fromHtml(msg), when);
notification.contentView = contentView;
String title = this.getString(R.string.app_name);
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List < ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClass().getSimpleName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
Intent notificationIntent;
if(!componentInfo.getPackageName().equalsIgnoreCase("com.example.myapp")){
notificationIntent = new Intent(getApplicationContext(),
FirstActivity.class);
} else {
notificationIntent = new Intent(getApplicationContext(),
MainActivity.class);
notificationIntent.putExtra("login", true);
}
notificationIntent.putExtra("message", Html.fromHtml(msg));
oldMessage = newMessage;
savePreferences(getApplicationContext(), oldMessage);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
int notifyID = 1;
PendingIntent intent = PendingIntent.getActivity(this, notifyID,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, title, msg, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.contentIntent = intent;
notificationManager.notify(notifyID, notification);
}
When I send the message I receive it in device with Android 4.2 for example but not in devices with Android 2.3. I'm debugging the app with Android 2.3 and I have put a breakpoint in the method onHandleIntent of the IntentService but it never comes. I think that it could be for the errors that appears in logcat.
How can I solve the problem for devices with Android 2.3?
Thanks in advance.
I change Notification to NotificationCompat:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentIntent(intent);
Notification notification = mBuilder.build();
notification.contentView = contentView;
notificationManager.notify(notifyID, notification);
but the problem persist, in logcat appears the same error
Try this code. I've used this in my project and it runs good. receiverActivity is activity that will open onclick, as I can remember, but I'm not 100% sure of it.
public static void showNotification ( Context context, Class receiverActivityClass, String title, String text, int icon )
{
Intent intent = new Intent( context, receiverActivityClass );
PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, intent, 0 );
// Build notification
Notification notification = new Notification.Builder( context )
.setContentTitle( title )
.setContentText( text )
.setSmallIcon( icon )
.setContentIntent( pendingIntent )
.setAutoCancel( true )
.getNotification();
NotificationManager notificationManager =
( NotificationManager ) context.getSystemService( context.NOTIFICATION_SERVICE );
notificationManager.notify( 0, notification );
}
I am using the following code to create a Notification inside the onRecieve method of my BroadcastReceiver but it is giving me the following exception:
java.lang.IllegalArgumentException: contentIntent required
The code:
NotificationManager notificationManager;
notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
String tickerText;
String expandedText;
String expandedTitle;
int icon;
long when;
Notification notification;
int notificationref = new Random().nextInt(100) + 1;
icon = R.drawable.reminder;
tickerText = "New Reminder";
when = System.currentTimeMillis();
notification = new Notification(icon, tickerText, when);
expandedText = "Reminder at: "
+ DateOrTimeString.getTimeString(task.time) + "\n"
+ task.detail;
expandedTitle = "Reminder:" + task.topic;
Intent intentDestroyer = new Intent(context, RemindHomeActivity.class);
intentDestroyer.putExtra("ID", task.id);
intentDestroyer.putExtra("NOTIFICATIONREF", notificationref);
launchIntent = PendingIntent.getActivity(context, notificationref,
intentDestroyer, 0);
notification.setLatestEventInfo(mContext, expandedTitle, expandedText,
null);
notificationManager.notify(1, notification);
One more thing this problem is only in API level less than 11. it is wortking in API level 15 Icecream Sandwitch
You need to set the contentIntent
void android.app.Notification.setLatestEventInfo(Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent)
in your case:
notification.setLatestEventInfo(mContext, expandedTitle, expandedText,
launchIntent );
I have the Problem, when a user press the Notification activity is opens but it can't be closed.
Here is my code:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Good Morning";
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, time);
Context context = getApplicationContext();
CharSequence contentTitle = "Title";
CharSequence contentText = "Text";
Intent notificationIntent = new Intent(this, NotificationManagerDemoActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1,notification);
try it like this..hope it will work..
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Set Auto Cancel to true while building Notification as follow.
notificationBuilder.setAutoCancel(true);
You should try to write code like below
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext(), "Channel")
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher_logo_round))
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher_logo_round);
mNotificationManager.notify(id,mBuilder.build());
.setAutoCancel(true)