I try to create android notification, when i click in a button but does not work.
this is the code that i write in button
NotificationManager Nm;
public void Notify(View view) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("LOGIN")
.setContentText("You are login successfully")
.setSmallIcon(R.drawable.done);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
}
As already stated by Ikazuchi, for android versions since android 8 you'll need to add a notification channel. This can be done, as it's shown in the documentation here: https://developer.android.com/training/notify-user/build-notification#java, like this:
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, "channelID")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.build();
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel serviceChannel = new NotificationChannel(
"channelID",
"Channel Name",
importance
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
Related
This is my code to receive notification
public class FirebaseMessageReceiver
extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageTitle,String messageBody) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
i am trying to received notification from firebase console i am able to get to get call back when fire notification i am also getting title and msg code executed successfully but i am unable to see notification in notification section of device can any one please help me what i am doing mistake .
Do you use notification channel?
If you are using Adroid 8 or higher it's expected behavior:
Starting in Android 8.0 (API level 26), all notifications must be
assigned to a channel or it will not appear.
https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels
Here you can find detail tutorial how to create notification channel:
https://developer.android.com/training/notify-user/channels
For devices running Android O or higher, you need to create a notification channel first in order to receive notifications like this:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("This is Channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
Also, you need to pass this CHANNEL_ID constant in NotificationCompact.Builder constructor like this:
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this, CHANNEL_ID)
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
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
I'm trying to periodically run a service even when the app is killed or is in the background using workManager.
My RequestService class is given below:-
public class RequestService extends Worker {
public RequestService(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
displayNotification("MY Worker", "Background work Started");
Log.i("BackJob","Running");
return Result.SUCCESS;
}
private void displayNotification(String title, String task){
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MyApp","My Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "My Notifications").
setContentTitle(title).setContentText(task)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.notify(130, notification.build());
}}
This is the main activity code:-
final PeriodicWorkRequest WorkReq = new PeriodicWorkRequest.Builder(RequestService.class,15,TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(WorkReq);
The issue is if the app is killed or is in the background then workmanager stops working.
I'm testing this on a samsung device with android version pie.
P.S :- if the app is open then i see notifications continuously after 15 mins....however as soon as i close the app.....it stops working.....and there are no more notifications
You can use foreground Service for this , Foreground Service work when app is in background.
add this method in downork method
setForegroundAsync(createForegroundInfo(progress));
Override this method in workermanager class
#NonNull
private ForegroundInfo createForegroundInfo(#NonNull String progress) {
Context context = getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel("1", "channelName", NotificationManager.IMPORTANCE_NONE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
}
Notification notification = new NotificationCompat.Builder(context, "1")
.setContentTitle("title")
.setTicker("title")
.setSmallIcon(R.drawable.ic_launcher_background)
.setOngoing(true)
.build();
return new ForegroundInfo(1,notification);
}
Now you app will work in the background.
As Per the PeriodicWorkRequest.Builder official documentation available here
The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
This value is currently set to 900000 ms i.e, 15 minutes.
This is a working example that currently shows any notification regarding the version of the SO. But seemingly the problem can be related with the notify method from NotificationManagerCompat
private void makeStatusNotification(String message, Context context) {
String channelId = context.getString(R.string.worker_sync_notif_channel_id);
// Make a channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel, but only on API 26+
CharSequence name = context.getString(R.string.worker_sync_notif_channel_name);
String description = context.getString(R.string.worker_sync_notif_channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Add the channel
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
// Create the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_cloud_upload)
.setContentTitle(context.getString(R.string.worker_sync_notif_title))
.setContentText(context.getString(R.string.worker_sync_notif_subject))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[0])
.setAutoCancel(true);
// Show the notification
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build());
}
I have a simple method which onclick() of a Button should generate status bar notification, but for some reason, it isn't showing up.
public void createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("Notification!")
.setContentText("This is my first notification!");
Notification notification = builder.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
}
In Android 8 (API level 26), all notifications must be assigned to a channel.
This work for me:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.emo_no_paint_120)
.setContentTitle("title")
.setContentText("content")
.setColor(Color.parseColor("#009add"))
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(
NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(0, mBuilder.build());
And you should add AppCompat library
implementation 'com.android.support:support-compat:27.1.0'
You could check official Android Docs
Your code is okay. But since you are targeting Android 8.0, you need to implement Notification Channels since this the preferred way in Android Oreo.
https://developer.android.com/guide/topics/ui/notifiers/notifications.html