I am trying to clear notification. But it remains there. Not able to open fragment Activity from notification. Below is my code,
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int sticky;
try {
AndroidLogger.log(5, TAG, "Missed call notification on start");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
NotificationChannel channel = new NotificationChannel("1", "Call Notification", importance);
channel.setDescription("Get alert for missed call");
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Intent notifyIntent = new Intent(this, ViewFragment.class);
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
.setSmallIcon(R.drawable.nexge_logo)
.setContentTitle("Missed Call")
.setContentText(intent.getStringExtra("Number"))
.setContentIntent(pIntent)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX);
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//mNotifyMgr.notify(1, buildNotification);
startForeground(1,buildNotification);
} catch (Exception exception) {
AndroidLogger.error(1, TAG, "Exception while starting service", exception);
}
return START_NOT_STICKY;
}
}
Anybody help me to solve this. Thanks in Advance.
Below is my another question for which I didn't get a proper answer. Help me with that also
About Notification for Missed Call in android
My solution to a similar issue has been changing PendingIntent Flag to PendingIntent.FLAG_ONE_SHOT
From Android documentation:
Flag indicating that this PendingIntent can be used only once. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
and adding notification FLAG_AUTO_CANCEL flag:
mBuilder.flags |= Notification.FLAG_AUTO_CANCEL;
which should make sure the notification will be removed once used.
Edit:
Should call
Notification notification = mBuilder.build();
first, then
notification.flags = Notification.FLAG_AUTO_CANCEL;
Edit2:
Just noticed that you are using the notification for startForeground(). This means that the notification will stay for as long as your Service / Activity is running (this is by default so the user will know that there is a Service / Activity still running).
The notification will stay for as long as your Service / Activity does run as foreground service.
Related
I have problem with my app for Android.
When I run my app using Android studio, I start a servis (foreground) and it works.
But When I disconnect my device from computer, and run service, he doesnt work.
I run NotificationListenerService.
Someone knows what could be the cause of this ?
Please help
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
"abc.eu", "xyzabc", NotificationManager.IMPORTANCE_HIGH
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, "abc.eu")
.setContentTitle("title")
.setContentText("Content")
.setContentIntent(pendingIntent).build();
startForeground(1, notification);
packageManager = getPackageManager();
apps = loadData(apps);
Log.d("MainService", "onStartCommand");
return START_STICKY;
}
You may be didn't stop the previous Foreground Service from launching the app for the first time, so when you launch it for the second time, it doesn't start a new Foreground service until the first one is over.
So, first Make sure that your foreground service is stopped by calling stopForeground(true) followed by stopSelf()
Confirm that there is no notification in status bar related to your app.
If still you face a problem: add PendingIntent.FLAG_ONE_SHOT in the pending intent so that this PendingIntent can be used only once
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
I searched many other questions related to this topic but found not satisfactory answer also none of them are working for me.
I want to show a continuous notification which should only be terminated by app. But the code i wrote was working a few days ago but not now.
private void GenNotification(String title, String body)
{
try
{
Log.i(Config.TAGWorker, "Generating Notification . . .");
Intent myIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setChannelId("myID")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(false)
.setSmallIcon(R.drawable.floppy)
.setOngoing(true)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
catch (Exception e)
{
Log.e(Config.TAGWorker, e.getMessage());
}
}
There is no exception recorded in Logcat, regarding ths. The code is called in onCreate of service. The service is starting correctly i can see in Log cat also there is no exception but notification is not shown. My OS is Android ONE for nokia (PI)
You are using a deprecated NotificationCompat.Builder constructor which takes a single argument (context); and that won't work on starting from Android 8.0 (API level 26).
So, to solve this:
Step 1: Create a Notification channel with the NotificationManager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Notification channels are only available in OREO and higher.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel
("PRIMARY_CHANNEL_ID",
"Service",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Description");
mNotificationManager.createNotificationChannel(notificationChannel);
}
Note: changeargument values as you wish
Step 2:: Use the non-deprecated Notification.Builder class with its two-argument constructor that takes a second argument as the channel ID which you assigned in the first step, where I set it to "PRIMARY_CHANNEL_ID"
Notification notification = new NotificationCompat.Builder
(this, "PRIMARY_CHANNEL_ID")
.setContentTitle("title")
.setContentText("body")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.build();
mNotificationManager.notify(0, notification);
Did you check your strings (title and body) is not null if it's null notification wont show
Also check that you call your notification channels when you start your service every time if your android above 7.0
Clear notification when you recall it same id in your case is 1.
This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I'm trying to pop up a notification when my alarm manager fires my onReceive() method. This is what I have done
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire(10000);
startNotification(context);
wl.release();
}
public void setAlarm(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(Activity, "MainActivity.class");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
assert am != null;
am.set(AlarmManager.RTC_WAKEUP, 60000, pi);
}
private void startNotification(Context context){
// Sets an ID for the notification
int mNotificationId = 001;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// Build Notification , setOngoing keeps the notification always in status bar
mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("RandomTitle")
.setContentText("RandomText")
.setOngoing(true);
// Create pending intent, mention the Activity which needs to be
//triggered when user clicks on notification(StopScript.class in this case)
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("extra","Extra Notificacion");
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
// context.startActivity(notificationIntent);
mBuilder.setContentIntent(contentIntent);
// Gets an instance of the NotificationManager service
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Android Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
// Builds the notification and issues it.
notificationManager.notify(mNotificationId, mBuilder.build());
}
Im really confused why this notification is not showing, I have tested my alarm and it triggers after 1 minute of beign created, but the notification is still not showing.
Any ideas?
thanks
From Android developer:
When you target Android 8.0 (API level 26), you must implement one or
more notification channels. If your targetSdkVersion is set to 25 or
lower, when your app runs on Android 8.0 (API level 26) or higher, it
behaves the same as it would on devices running Android 7.1 (API level
25) or lower.
Because your targetSdkVersion is 28, so you must add channelId in the Builder constructor too.
Change your code to:
// Build Notification , setOngoing keeps the notification always in status bar
mBuilder = new NotificationCompat.Builder(context, "notify_001") // Add channel ID to the constructor.
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("RandomTitle")
.setContentText("RandomText")
.setOngoing(true);
As per Android Developers Documentation :
NotificationCompat.Builder
NotificationCompat.Builder (Context context)
This constructor was deprecated in API level 26.1.0. use
NotificationCompat.Builder(Context, String) instead. All posted
Notifications must pecify a NotificationChannel Id.
Reference here
Edit:
Try the following :
Leave the NotificationCompat.Builder as it is now (with a string
representing NotificationChannel) .
Comment out your if block where you create a notification channel
Replace your NotificationManager with NotificationManagerCompat as the following :
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(mNotificationId, mBuilder.build());
Faced with the problem of displaying notifications in android Lollipop. When app is open notifications shows app fine, but when the application is closed they are not displaying. On 4x versions of android everything works properly. Here is a method to display them
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void sendNotification(String body, String title, String badge) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("from_notify", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(badge), intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText(body)
.setPriority(Notification.PRIORITY_HIGH)
.setShowWhen(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
I think this is the problem:
when your app is closed,all app's data will be cleared including the notifications and statics data,so if you want to make notifications alive all the time you have to send it from service(create service class and run it in the background).
try this:
public class YourService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//send your notifications here
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
note that you can send notifications from other classes not just from service class,but you have to run a service in the background because it helps to keep statics data for your app after it is closed.this worked for me.
I hope this will help you.
I am working on a small project that involves a web interface that can send information to my android app which will display such information as Push Notifications.
But here is the thing, I am a bit confused with how to do that. As in what step will i have to take.
So I have a web interface in HTML which has a Textfield for notification Title, Content, and a submit button. I want it that when the user clicks the Submit button, the webpage will send the text that s in the Title and Content fields to my android app and then the app will just display them as push notifications.
So far on the app i have it that when you click a button on your device then it just shows a notification on the Actionbar. This is great for testing but It would be better that you can just compose your notification through a web interface.
My test Push Notification code for the app:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
// TODO: Make this accessible to exterior projects, such as web interface.
Notification notification = new Notification.Builder(MainActivity.this)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nManager.notify(0, notification);
}
});
If anyone could be so kind to give me a hand, it would be much appreciated.
You are right, so far so good with the notification bar, now what you need is a notification service, and google has something like that for us...
how does this works??
Take a look at the image below,
you need to register your android app in the google service, and your web interface will need an id, so everytime you want to push something to the android, your web interface instead will push it to the google server with the Id of the app, then google (no matter how) will localize your app, and even if its not running, they will get the notification,
behind the scenes there is a couple of thing that you must do, bu nothing like launching rockets from the NASA.
I will suggest to take a look to some tutorials
in order to start with the registration of your app, get the api key etc etc..
Here is a great source in github which shows how you can add push notification service in your android app
github.com/rana01645/android-push-notification
Firstly read the full documentation
How to add push notification in android application from android studio – Android developer (part – 1 Connect with firebase ) ~ http://androidrace.com/2016/12/08/how-to-add-push-notification-in-android-application-from-android-studio-android-developer-part-1-connect-with-firebase/
How to add push notification in android application from android studio – Android developer (part – 2 Working with server) ~http://androidrace.com/2017/01/05/how-to-add-push-notification-in-android-application-from-android-studio-android-developer-part-2-working-with-server/
Then you can able to send push notification from your server using html
public class Uyarilar extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
Date currentTime = Calendar.getInstance().getTime();
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.presta)
.setContentTitle("Saat 9:00")
.setContentText("Mesai saatiniz başlamıştır Lütfen harakete geçiniz!");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
and call
private void setNotification() {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, 9);
calSet.set(Calendar.MINUTE, 00);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if (calSet.compareTo(calNow) <= 0) {
calSet.add(Calendar.DATE, 1);
}
Date currentTime = Calendar.getInstance().getTime();
Intent intent = new Intent(getBaseContext(), Uyarilar.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);
}
and
onCreate
setNotification();
this method to push notification
public void testMessage (String message , Intent intent){
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "some_channel_id";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder =
new android.support.v4.app.NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setBadgeIconType(android.support.v4.app.NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
assert notificationManager != null;
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}