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);
}
Related
Be informed, we are trying to send notification with a button using Addaction. The button Start has a intent that directly opens a url in a webview, which works perfectly fine with code given below
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uri", uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//int notification_id = nid!=null ? Integer.parseInt(nid) : MainActivity.ASWV_FCM_ID;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
int notification_id=m;
Intent buttonIntent = new Intent(this, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",notification_id);
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);
String channelId = MainActivity.asw_fcm_channel;
Uri soundUri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/pristine");
NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, tag, pendingIntent).build();
NotificationCompat.Action action1 = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Dismiss", btPendingIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder1 = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(false)
.addAction(action)
.addAction(action1)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
// Configure the notification channel.
mChannel.setDescription("Common notifications");
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setSound(soundUri, attributes);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(mChannel);
}
Notification noti = notificationBuilder1.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notification_id, notificationBuilder1.build());
Update:
I'm sorry but i'm not actually a expert or a regular coder in android java, so you gotta help me here a little bit more. I have passed on my notification id down in the code, but the problem here is how do i invoke removeNotification in the pendingIntent which also carries my url to where the link will go onclick
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uri", uri);
intent.putExtra("notificationId",notification_id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
public static void removeNotification(int notification_id) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notification_id);
}
} catch (Exception e) {
}
}
But we also like the notification to be dismissed simultaneously onclick. We tried using .setAutocancel (true) and notification flags like FlAG_AUTO_CANCEL, but the button just does first action right of going into webview url and not cancelling the notification.
Shall appreciate should you help us out.
Send the notification id in the intent to activity and use the code to cancel.
public static void removeNotification(Context context, int notification_id) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notification_id);
}
} catch (Exception e) {
Timber.d(e);
}
}
Intent intent = getIntent();
if (intent.hasExtra("notificationID")) {
removeNotification(context, intent.getIntExtra("notificationID", 0));
}
I have receive three different screens in my app:
Reading,
Walking, and
Sleeping
How do I identify the specific notification to redirect to in each screen?
To do so, you must specify a content intent defined with a PendingIntent object and pass it to setContentIntent().
The following snippet shows how to create a basic intent to open an activity when the user taps the notification:
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, Reading.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
This is clearly mentioned in Android developer site
private final String CHANNEL_ID = "channel1";
private final String CHANNEL_NAME = "channel_one";
private NotificationManager notificationManager;
private NotificationManager getNotificationManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
} else {
return notificationManager;
}
}
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("type", "type");
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setShowBadge(true);
getNotificationManager().createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setColorized(true);
builder.setChannelId(CHANNEL_ID);
builder.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Title");
builder.setContentText("Message");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_bottom_logo);
builder.setLargeIcon(/*BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)*/getBitmapFromDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.ic_launcher)));
builder.setContentIntent(pendingIntent);
getNotificationManager().notify((int) SystemClock.uptimeMillis(), builder.build());
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 creating a notification upon click I am asking it cancel a service. It just works fine below 4.4 (Kitkat). My app supports 2.2 (API 8 onwards)
On Kitkit (Nexus 5) The service isn't called at all. I am not where I am going wrong here? It just works fine even on version 4.3?
Here is what I have tried and working on every phone except Nexus 5(Kitkat)
createNotification("Click here to cancel notification!", "TestApp");
I am calling the above immediately after calling a particular service.
private void createNotification(String body,String title)
{
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
int unique_id = 007;
Intent nintent = new Intent(this,ServicetocancelAlarm.class);
PendingIntent pin = PendingIntent.getService(this,0, nintent, 0);
//set notify image
Notification n = new Notification(R.drawable.ic_launcher, body,java.lang.System.currentTimeMillis());
n.contentIntent = pin;
n.setLatestEventInfo(this, title, body, pin);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(unique_id, n);
}
Can somebody help me out fixing this issue with KITKAT?
Update:
I tried the following:
Notification("Message", "This is Android Notification Message");
And Method
#SuppressWarnings("deprecation")
private void Notification(String notificationTitle, String notificationMessage)
{
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
android.app.Notification notification = new android.app.Notification(R.drawable.ic_launcher, "A New Message",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, TransparentActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(MainActivity.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
This piece of code works fine on debug mode but if Export the apk and install it. It just doesn't work at all. It doesn't get to the new activity. I am not sure what is wrong here.
I solved the problem by trying the following code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 16)
{
Context context = RepeatService.this;
Intent notificationIntent = new Intent(context, ServicetocancelAlarm.class);
PendingIntent contentIntent = PendingIntent.getService(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = context.getResources();
Notification.Builder builder = new Notification.Builder(context);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.ticker))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(res.getString(R.string.app_name))
.setContentText(res.getString(R.string.cancelText));
Notification n = builder.build();
nm.notify(007, n);
}
Else part has the usual notification code that just works fine below API 16..
try it out!!
I reasearched this, and this code is what I got
The app crashes when I open the MainActivity
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Get Other APW Co. Apps on Play!")
.setContentText("Want more? All our apps are free!");
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemmService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, builder.build());
Try this, Give context name getSystemmService(Context.NOTIFICATION_SERVICE);.
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher,
"Notification!", System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "App Name";
String notificationText = Msg;
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog),
context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,
0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context, notificationTitle,
notificationText, pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
This will work:
notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher,
"Notification!",
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Get Other APW Co. Apps on Play!";
String notificationText = ""Want more? All our apps are free!"";
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(SOME_URL));
PendingIntent pendingIntent
= PendingIntent.getActivity(AndroidNotification.this,
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(1, myNotification);
}});
You have to specify contentIntent, i.e. the PendingIntent that will be executed when the item is clicked. It's mandatory, and you haven't specified it which causes the error.
You can do this in the builder or on the Notification:
in builder:
builder.setContentIntent(contentIntent);
Notification n = builder.build();
on Notification:
Notification n = builder.build();
n.contentIntent = contentIntent;
Only after can you send it to the NotificationManager:
mNotifyMgr.notify(mNotificationId, n);
The exact contentIntent value depends on what you want to do. See reference here:
http://developer.android.com/reference/android/app/Notification.html#contentIntent
See working example here: https://github.com/nheid/unitedcoders-android/blob/master/src/com/unitedcoders/android/examples/download/DownloadProgress.java