Android foreground service notification not showing in status bar - java

I have tried various solution here on SO and can't seem to get any of them to work. The notification simply will not show. Can anyone point out where possible issues in my code could be?
private void startRunningInForeground() {
setupNotificationChannel();
Intent showTaskIntent = new Intent(getApplicationContext(), MainActivity.class);
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, SERVICE_NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_stat_ic_logo);
builder.setContentTitle(getString(R.string.merge_notif_title));
builder.setContentText(getString(R.string.merge_notif_description));
builder.setContentIntent(contentIntent);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setOngoing(true);
startForeground(NOTIFICATION_ID, builder.build());
}
private void setupNotificationChannel() {
// Only run this on versions of Android that require notification channels.
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager == null) {
return;
}
NotificationChannel cachingChannel = new NotificationChannel(SERVICE_NOTIFICATION_CHANNEL,
getString(R.string.merge_channel), NotificationManager.IMPORTANCE_HIGH);
cachingChannel.setDescription(getString(R.string.merge_channel_description));
cachingChannel.enableLights(false);
cachingChannel.enableVibration(false);
notificationManager.createNotificationChannel(cachingChannel);
}
Not receiving any any error messages and the notification channel is being created because I see it in the app settings.

What does your startForeground do?
try modify this and make sure your os is > Android 8.0
btw the Channel only needs to be created once.
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
NOTIFICATION_ID, <---
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
startForeground(NOTIFICATION_ID, builder.build());
notificationManager.notify(NOTIFICATION_ID, builder.build()); <--
Maybe because of Android O bg service restrictions
//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, YourService.class));
} else {
startService(new Intent(this, YourService.class));
}

So I was able to get it to work by extending Service instead of IntentService. I cannot give an explanation as to why this worked, but everything is now working as expected.

Related

Notification Manager creates only one notification channel but i need to create three channels

in my application, i have created 3 notification channels (Follow, Comment, Like) to receive notifications from Firebase Cloud Messaging.
When i run app and go to Settings > Apps > My App > App Notifications , I found it show only one notification channel (ex. Follow channel) and other two channels are't be shown ...
But when i receive notification from Comment channel for example, it updates current channel with Comment channel and when i receive notification from Like channel, it updates current channel with Like channel and so on..
so why it doesn't show three channels as separated channels at same time ?!
Here is Code I work with:
public class MyFireBaseMessagingService extends FirebaseMessagingService {
String title, content, type;
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
title = remoteMessage.getData().get("Notif_Title");
content= remoteMessage.getData().get("Notif_Content");
type = remoteMessage.getData().get("Type");
if (type.equals("Follow")) {
NotificationManager manager1 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent result = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, result, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(postContent)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent)
//to work on android 8 and high..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("YOUR_PACKAGE_NAME");
builder.setSmallIcon(R.drawable.logo);
NotificationChannel channel = new NotificationChannel(
"YOUR_PACKAGE_NAME",
"Follow",
NotificationManager.IMPORTANCE_HIGH);
manager1.createNotificationChannel(channel);
}
manager1.notify(0, builder.build());
} else if (type.equals("Comment")) {
NotificationManager manager2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent result = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 1, result, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(content)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent)
//to work on android 8 and high..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("YOUR_PACKAGE_NAME");
builder.setSmallIcon(R.drawable.logo);
NotificationChannel channel = new NotificationChannel(
"YOUR_PACKAGE_NAME",
"Comment",
NotificationManager.IMPORTANCE_HIGH);
manager3.createNotificationChannel(channel);
}
manager3.notify(1, builder.build());
} else if (type.equals("Like")) {
Intent result = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 2, result, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager manager3 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title))
.setContentText(content)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent)
//to work on android 8 and high..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("YOUR_PACKAGE_NAME");
builder.setSmallIcon(R.drawable.logo);
NotificationChannel channel = new NotificationChannel(
"YOUR_PACKAGE_NAME",
"Like",
NotificationManager.IMPORTANCE_HIGH);
manager3.createNotificationChannel(channel);
}
manager3.notify(2, builder.build());
}
}
}
Can Anyone help me...
I know how to solve it ...
You should change this code
builder.setChannelId("YOUR_PACKAGE_NAME");
builder.setSmallIcon(R.drawable.logo);
Into specific channel id to each one like :
builder.setChannelId("com.myapp.first_notification");
builder.setSmallIcon(R.drawable.logo);

Heads up notification not showing in android O and higher

I literally have tried everything seriously every method and every snippet but still, I was not able to show heads-up notifications on Chinese brand devices.
so yesterday I thought why not try it again but after all again still I'm not able to show heads-up notification until I manually goto the app into the settings and give floating permission for the app.
Now most of you may say why not to navigate the user to the setting when he/she first opens up the app but nobody likes that even there are other apps (I'm not talking about white list app like WhatsApp) which have 10K downloads are able to show heads up notification
Here is my code, btw I have tried setting the sound, vibration, and light but still heads up are not showing, and yes I do uninstall my app after every build
public void showNotification(View v){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel("n","pop up notification", NotificationManager.IMPORTANCE_HIGH);
nc.enableLights(true);
nc.setLightColor(Color.BLUE);
nc.enableVibration(true);
nc.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager nm = getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
Notification.Builder notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notification = new Notification.Builder(this,"n")
.setContentTitle("Pop up notification")
.setSmallIcon(R.drawable.ic_launcher_background);
}else{
notification = new Notification.Builder(this)
.setContentTitle("Pop up notification")
// .setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher_background);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notification.build());
}
I have two solutions. Try them out and see if any works.
Yours actually works Like this
public void showNotification(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel("n","pop up notification", NotificationManager.IMPORTANCE_HIGH);
nc.enableLights(true);
nc.setLightColor(Color.BLUE);
nc.enableVibration(true);
nc.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager nm = getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
Notification.Builder notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notification = new Notification.Builder(this,"n")
.setContentTitle("Pop up notification")
.setSmallIcon(R.drawable.alex);
}else{
notification = new Notification.Builder(this)
.setContentTitle("Pop up notification")
//.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.alex);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notification.build());
Mine notifyUser("Order Delivery", "Your order has arrived"):
public void notifyUser(String title, String text){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "notify_001");
Intent intent = new Intent(this, ActivityToOpenWhenNotificationIsTapped.class);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(text);
bigTextStyle.setSummaryText("Big summary text. Comment if you want.");
builder.setAutoCancel(true);
builder.setContentIntent(activity);
builder.setContentTitle(title);
builder.setContentText(text);
builder.setPriority(1);
builder.setSmallIcon(R.drawable.alex);
builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.alex));
builder.setStyle(bigTextStyle);
builder.setAutoCancel(true);
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
builder.setGroup("Pixels");
Notification build = builder.build();
build.flags |= 16;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= 26) {
String str3 = "Pixels_V1.0";
notificationManager.createNotificationChannel(new NotificationChannel(str3, "Pixels Notification", NotificationManager.IMPORTANCE_DEFAULT));
builder.setChannelId(str3);
}
int NOTIFICATION_ID = new Random(System.currentTimeMillis()).nextInt(1000);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}

Running a function after the app opens from the background after notification click

I'm pretty new to Android development. I have been able to get a notification to pop up while the app is in the background. When I click on it, it successfully loads the application backup. However I want to load an Alert from the page but only when it is opened from a notification click.
Here is the code for generating the notification. Any help would be appreciated.
private void getNotificationForPasswordChange() {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Hello";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
if (mNotificationManager != null)
mNotificationManager.createNotificationChannel(mChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent mainIntent = PendingIntent.getActivity(this, 0,
i, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Pronto Tracker")
.setTicker("Pronto Tracker")
.setContentText("Cannot connect to server. Location is not being updated.")
.setSmallIcon(R.mipmap.ic_pronto_logo)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setOngoing(true).setContentIntent(mainIntent).
build();
mNotificationManager.notify(Constants.PASSWORD_CHANGE_NOTIFICATION_ID, notification);
}
You can pass the alert message with notification PendingIntent. Add the message or value you want to show as alert in PendingIntent .putExtra() and also specify the activity in PendingIntent where you want to show the alert in form of dialog or anything.
Intent intent = new Intent(Application.getAppContext(), MainActivity.class);
intent.putExtra("is_notification", true);
intent.putExtra("alert_message", "Hello World!");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
After that add the PendingIntent to your notification.
Second thing you need to do is to get the data from the Intent when user taps on notification.
In your MainActivity add the following code to get data from Intent:-
if (getIntent() != null) {
String message = getIntent().getStringExtra("alert_message");
boolean isNotification = getIntent().getBooleanExtra("is_notification", false);
if(is_notification){
// show alert
}
}
You should use onCreate function on your MainActivity
Add this code to parce your intent:
Intent receivedIntent = getIntent();

Clear app notifications in android studio

I have an application that sends notifications, but when the user leaves the application the notification is still there, in case he does not click on it.
So, when the user logs out, or the session user is "null", the notifications will be automatically deleted.
My code:
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void enviarNotificacao(){
Intent intent = new Intent(this, BottomNavigation.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.putExtra("totens", listaTotem);
int id = (int) (Math.random()*1000);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("Olá Marujo!!!");
builder.setContentTitle("Capitão Cupom");
builder.setContentText("Um novo tesouro próximo de você");
builder.setSmallIcon(R.drawable.logo);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
builder.setContentIntent(pi);
builder.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id, builder.build());
Notification n = builder.build();
n.vibrate = new long[]{150, 300, 150, 600};
notificationManager.notify(R.drawable.logo, n);
try {
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(this, som);
toque.play();
}catch (Exception e){
}
Sessao.instance.setSailor(sailor);
}
NotificantionManager.cancel(id) cancels a notification with that id. NoticiationManager.cancelAll() cancels all notifications from this app. Detecting when a session ends will obviously be business logic you need to build. When it happens, call one of the 2 above functions.
Override onPause() in Activity and put this inside:
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
When leaves the application call it
notificationManager.cancel(NOTIFICATION_ID);

Creating notification when app is closed

I am using the onDestroy method, which I have learned is not always called when app is closed. And this has created a problem for me, where I would like to have the notification pop up every time the app closed. Is there a better way to do this? By the way, onStop and onPause are not options for me, because my app runs as a background service. Interestingly, my onDestroy method works everytime my background service is running, but whenever it is turned off, and just the app interface is open, my onDestroy never is called. This seems weird because I thought that onDestroy isn't called if the device is lacking resources, and running my service would be taking up more resources than not. Idk. Any help on this would be greatly appreciated!
`#Override
public void onDestroy(){
super.onDestroy();
Log.d("asdasd","asdasdasdasdasd");
if(notif.isChecked()) {
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("S-Dimmer")
.setContentText(getResources().getString(R.string.sDimmerStopped))
.setSmallIcon(R.drawable.ic_action_name1)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_NO_CLEAR;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
doas.isRunning = false;
}
}`
This method is not always called, so you should try from background service, as there's also some destruction process alert.
So please try to do what ever you want there in the services.
Please check out this ..
onDestroy() may or may not be called on any given activity or service. The general rule is that either onDestroy() is called, or your process is terminated, or your code crashed.
You don't. Your process may be terminated for any reason, at any time, by the user or by the OS. You may or may not be called with onDestroy() when that occurs. While you may be able to improve your success rate a little via onTaskRemoved() on a Service, this itself has proven unreliable, and it will not cover all scenarios.
you are doing it wrong way. In onDestroy method all other stuffs should implemented before super.onDestory()
try this
#Override
public void onDestroy(){
Log.d("asdasd","asdasdasdasdasd");
if(notif.isChecked()) {
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("S-Dimmer")
.setContentText(getResources().getString(R.string.sDimmerStopped))
.setSmallIcon(R.drawable.ic_action_name1)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_NO_CLEAR;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
doas.isRunning = false;
}
super.onDestroy();
}`
onTaskRemoved()
{
if(notif.isChecked()) {
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("S-Dimmer")
.setContentText(getResources().getString(R.string.sDimmerStopped))
.setSmallIcon(R.drawable.ic_action_name1)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_NO_CLEAR;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
doas.isRunning = false;
}
}

Categories

Resources