foreground service notification in lockscreen - android

I'm trying to achieve a foreground service.
my problem is my notification doesn't appear in the lock screen.
I try to set visibility to PUBLIC but it doesn't work.
#RequiresApi(api = Build.VERSION_CODES.O)
private String createNotificationChannel() {
NotificationChannel notificationChannel =
new NotificationChannel(
"channelId",
"channelName",
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("channelDescription");
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
NotificationManagerCompat service = NotificationManagerCompat.from(getBaseContext());
service.createNotificationChannel(notificationChannel);
return "myChannelId";
}
public void startForeground() {
Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
String channelID = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelID = createNotificationChannel();
}
Notification notification = new NotificationCompat.Builder(this, channelID)
.setContentTitle(title)
.setContentText(content)
.setShowWhen(false)
.setSmallIcon(R.drawable.ic_notification_small_icon)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.build();
startForeground("notificationId", notification);
}

notification.setOngoing(true)
makes the notification visible on your lock screen.
Code
Notification notification = new NotificationCompat.Builder(this, channelID)
.setContentTitle(title)
.setContentText(content)
.setShowWhen(false)
.setSmallIcon(R.drawable.ic_notification_small_icon)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
if that doesn't work check your device settings.
https://stackoverflow.com/a/26932991/9017620

Related

I have problem in custom notification in android

Here is my firebase messaging service code file. My service is not called.
public class NotificationService extends FirebaseMessagingService {
String myTitle, myImage;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
myTitle = remoteMessage.getData().get("title");
myImage = remoteMessage.getData().get("body");
Log.d("Service","Hi this is service");
//bitmap = getBitmapfromUrl(myImage);
//Toast.makeText(this,"Hi test",Toast.LENGTH_SHORT).show();
showNotification(myTitle,myImage);
}
private void showNotification(String myTitle,String myImage) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("Notification_Title", "yes");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Toast.makeText(this,title,Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "Custom_Notification";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notifications_none_white_24dp)
.setContentTitle(myTitle)
.setContentText(myImage)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Custom Notification",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
If you are not received any remote message or your service is not working mean, check out the StackOverflow link.
To Create Custom Notification Channel
private void showNotification(String myTitle,String myImage) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("Notification_Title", "yes");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "Custom_Notification";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notifications_none_white_24dp)
.setContentTitle(myTitle)
.setContentText(myImage)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Custom Notification",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build()); }
Above code is working fine after receiving the remote message. If you want to add any custom layout then use below code
// Get the layouts to use in the custom notification
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);
// Apply the layouts to the notification
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.build();
Notification custom layout
Note: In android 10, and above Notification Service is not calling basically in the background. You will receive a notification but custom design it will not reflect. Still, If you want to receive notification in the background also. then listen to the broadcast receiver for firebase message event. that time you have to wake up your app to the foreground.

BigPictureStyle Notification not working in AndroidX

Code:
here is the code to popup notification on button click
notificationbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "noti", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getActivity(),OrderTrack.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),(int) Calendar.getInstance().getTimeInMillis(),i,0);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.half_bicycle);
Notification builder=new NotificationCompat.Builder(getActivity(),"1")
.setSmallIcon(R.drawable.half_bicycle)
.setContentTitle("title")
.setContentText("Text")
.setLargeIcon(bitmap)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build();
Notification notif = new Notification.Builder(getContext())
.setContentTitle("New photo from ")
.setContentText("subject")
.setSmallIcon(R.drawable.half_bicycle)
.setLargeIcon(bitmap)
.setStyle(new Notification.BigPictureStyle()
.bigPicture(bitmap))
.build();
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);
});
Here I am trying to use BigPictureSt
yle notification. I hava tried two variation of code. But both doesn't give any result/notification.
All the above code is inside a fragment.Is this a reason why it's not working?
I have set the App style to NoActionBar.Is this a reason why it's not working?
Please answer this questions with a proper solution !!!!
Adding the Following code doesn't solve the problem
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);
The code is fine and there is nothing wrong with it but most importantly you forgot to show the notification itself i.e you are not using the objects that are created.
So show the notification like this...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);//101 is notification id
EDIT:
If you are targetting Android Oreo and above you need to create the channels for notification like this. Use this function to create notification channel and set this channel id on a notification while creating it...
String channelId = "some_channel_id";
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Complete code:
notificationbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createNotificationChannel(); //Create notification channel
Toast.makeText(getContext(), "noti", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getActivity(),OrderTrack.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),(int) Calendar.getInstance().getTimeInMillis(),i,0);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.half_bicycle);
Notification builder=new NotificationCompat.Builder(getActivity(),"1")
.setSmallIcon(R.drawable.half_bicycle)
.setContentTitle("title")
.setContentText("Text")
.setLargeIcon(bitmap)
.setChannelId(CHANNEL_ID) // Channel Id
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build();
Notification notif = new Notification.Builder(getContext())
.setContentTitle("New photo from ")
.setContentText("subject")
.setSmallIcon(R.drawable.half_bicycle)
.setLargeIcon(bitmap)
.setChannelId(CHANNEL_ID) // Channel Id
.setStyle(new Notification.BigPictureStyle()
.bigPicture(bitmap))
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);//101 is notification id
}
});
For more info visit this : https://developer.android.com/training/notify-user/channels

Android Notification with pending URL-Intent - only by clicking the notification

I'm trying to create a pending URL-Intent for a Notification, that is called, if the user clicks the notification.
The problem is that the Intent is being called by creating the notification, so the url is getting called in the web browser immediatly. I want to prevent this, but do not know how?
Here is my code
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.com"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(MyApp.getContext(), 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MyApp.getContext(), "MyApp")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("my App")
.setContentText("Click here to call the URL")
.setStyle(new NotificationCompat.BigTextStyle().bigText("...."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
;
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MyApp.getContext());
notificationManager.notify(getNotificationId(), builder.build());
How can I prevent executing the intent after the "notify" call??
Intent should only be executed, when the user clicks on the Notification.
try this:
public void notification()
{
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("https://www.google.com/"));
#SuppressLint("WrongConstant") PendingIntent pending =
PendingIntent.getActivity(this, 0, notificationIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
String channelId = getString(R.string.app_name);
NotificationChannel notificationChannel = null;
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getApplicationContext());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(channelId, channelId,
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription(channelId);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new
NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("my App")
.setContentText("Click here to call the URL")
.setStyle(new NotificationCompat.BigTextStyle().bigText("...."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pending)
.setAutoCancel(true)
;
notificationManager.notify(0, builder.build());
}

Notification auto disappear after showing

public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(context, AlertDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // added new line
intent.putExtra("STARTED_BY_RECEIVER", true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String CHANNEL_ID = "channel id";// The id of the channel.
CharSequence name = "Channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
Notification notification = new Notification.Builder(context)
.setContentIntent(pendingIntent)
.setContentText("Some Text")
.setContentTitle("Notification")
.setAutoCancel(true)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_notification_praying)
.setChannelId(CHANNEL_ID)
.build();
notificationManager.createNotificationChannel(mChannel);
notificationManager.notify(100 , notification);
} else {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(context, AlertDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // added new line
intent.putExtra("STARTED_BY_RECEIVER", true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification_praying)
.setContentIntent(pendingIntent)
.setContentText("Some Text")
.setContentTitle("Notification")
.setAutoCancel(true)
.setOngoing(true);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
notificationManager.notify(100, builder.build());
}
}
I've made an application which show notification on time that user chose in main activity and Notification should disappear only when user tap on notification otherwise not..and it was working fine unless I've updated my phone to android Oreo (8.0) now notification show at time but auto disappear after sometime.. How to make notification not auto disappear (in android Oreo) but only when user tap on it?
alright I figure this out.. it was battery optimize option which was killing my application so that's why notification was disappearing.. I removed my application from auto optimize now it's working fine.

Notification not showing up on Android 8

I've read most question/answers on this but my notification still isn't showing up.
My Broadcast receiver gets called, but then nothing happens. There is no error message nor exception. here is my code:
public class AlarmReceiver extends BroadcastReceiver {
private static int notificationId = 0;
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "mychannel")
.setSmallIcon(R.drawable.icon_awake)
.setContentTitle("MyAlarm")
.setContentText("Something")
.setAutoCancel(false)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId++, mNotifyBuilder.build());
}
}
I think you forget to Read Google Documents on Oreo 8.0.
If you want to create a notification on 8.0 you need to use NotificationChannel
like this:
NotificationChannel channel = null;
String chanel = "MY_Musixbox";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
channel = new NotificationChannel(chanel, "MusicBox", importance);
notificationManager.createNotificationChannel(channel);
}
And then add your notification
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "mychannel")
.setSmallIcon(R.drawable.icon_awake)
.setContentTitle("MyAlarm")
.setContentText("Something")
.setChannelId(chanel);
.setAutoCancel(false)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId++, mNotifyBuilder.build());
Okay, so I will answer this myself in case somebody finds it: seems you need to manually create the notification channel yourself too:
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel("mychannel",
"Channel name",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Channel description");
notificationManager.createNotificationChannel(channel);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "mychannel")
.setSmallIcon(R.drawable.icon_awake)
.setContentTitle("MyAlarm")
.setContentText("Something")
.setAutoCancel(false)
.setWhen(System.currentTimeMillis())
.setChannelId("default_channel")
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId++, mNotifyBuilder.build());
Try this. you have to define channel id. thats compulsory in android 8.0

Categories

Resources