So I am trying to create a notification at the top of the phone, but when I run my code it does nothing. Not even a single error. ??? What am I doing wrong here?
public void createNotification(Context ctx) {
SharedPreferences settings = ctx.getApplicationContext().getSharedPreferences(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, 0);
String contactName = settings.getString("curName", String.valueOf(0));
String contactEmail = settings.getString("contactEmail", String.valueOf(0));
String contactNumber = settings.getString("curPhone", String.valueOf(0));
String dueAmount = String.valueOf(settings.getInt("amountDue", 0));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setSmallIcon(R.drawable.myanlogo);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("LETTING YOU KNOW");
builder.setContentText("Your notification content here.");
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
I have it inside a class like this:
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder>
And I am calling the function here:
holder.textDueTomorrow.setVisibility(View.GONE);
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber) - 1) {
holder.textDueTomorrow.setVisibility(View.VISIBLE);
createNotification(context);
}
Some advice would be nice because I have been working at this for a while now.
It looks like you're missing Notification Channels for Build.VERSION_CODE.O and greater
https://developer.android.com/develop/ui/views/notifications/channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(notificationText);
// Set big text style.
builder.setStyle(bigTextStyle);
} else {
builder.setContentTitle(title);
builder.setContentText(notificationText);
}
This Chanel link below hellped me out along with the example provided below.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(notificationText);
// Set big text style.
builder.setStyle(bigTextStyle);
} else {
builder.setContentTitle(title);
builder.setContentText(notificationText);
}
This link makess it more clear. notification channel is not sending notifications Its basically 100% fine he just forgot to call function createNotificationChannel() before creating the notification.
For Android 8 and higher versions, you need to create a notification channel, write before your notification builder and pass same channel id to NotificationCompat.Builder
Copy/Paste this:
public void createNotification(Context ctx) {
createNotificationChannel();
SharedPreferences settings = ctx.getApplicationContext().getSharedPreferences(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, 0);
String contactName = settings.getString("curName", String.valueOf(0));
String contactEmail = settings.getString("contactEmail", String.valueOf(0));
String contactNumber = settings.getString("curPhone", String.valueOf(0));
String dueAmount = String.valueOf(settings.getInt("amountDue", 0));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, "CHANNEL_ID");
builder.setSmallIcon(R.drawable.myanlogo);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("LETTING YOU KNOW");
builder.setContentText("Your notification content here.");
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
I have update this line NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, "CHANNEL_ID");
JAVA
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("CHANNEL_ID", "Updates", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
KOTLIN
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
val notificationChannel = NotificationChannel("CHANNEL_ID", "Updates", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}
Related
I'm currently trying to implement a push notification into my app, that will be sent as soon as there's an internet connection. The service for checking the connection works just fine and the showNotifications() Method is being called. But the Notification won't show up in the bar. This is the code:
private void showNotifications(){
Intent intent = new Intent(APITest2.this, Start.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("notif","notify");
PendingIntent contentIntent = PendingIntent.getActivity(APITest2.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder= new NotificationCompat.Builder(APITest2.this)
.setSmallIcon(R.drawable.ic_android)
.setContentTitle("Title")
.setContentText("Text")
.setAutoCancel(true);
builder.setContentIntent(contentIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,builder.build());
}
Am I missing something?
Thanks in advance for any help!
Use notification manager like below to support all android versions
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.package.name");
NotificationChannel channel = new NotificationChannel(
"com.package.name",
"AppName",
NotificationManager.IMPORTANCE_HIGH
);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
notificationManager.notify(0, builder.build());
Create channel as like below,
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
String characterSequence = "Message Alert";
NotificationChannel channel = new NotificationChannel(channelId,
characterSequence,NotificationManager.IMPORTANCE_DEFAULT);
channel.setSound(soundUri,audioAttributes );
NotificationManager manager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
You need to pass channel id here like below,
NotificationCompat.Builder builder= new NotificationCompat.Builder(APITest2.this,channelId)
Also refer https://developer.android.com/training/notify-user/channels
If you need to show heads up notification, then you need to set Importance level in Notification Channel as IMPORTANCE_HIGH. And need to set priority in notification builder as below.
setPriority(NotificationCompat.PRIORITY_HIGH);
I want to open a specific folder(in storage via File Manager) by clicking on the notification. When I click on the notification, nothing happens with the code that I've provided, neither there is an error in the logcat. What changes should I make in my current code?
I've gone through following answers already, none of these seem to work
Android: How to open a specific folder via Intent and show its content in a file browser?
The following answer doesn't take me to the required folder:-
https://stackoverflow.com/a/17173655
Here is my code:-
public void sendNotif(String path)
{
Uri selectedUri = Uri.parse(android.os.Environment.getExternalStorageDirectory() + "/" + "App_Ka_Kaam/Electricity/"+pathway+"/");
Intent intent = new Intent(Intent.ACTION_VIEW,selectedUri);
intent.setDataAndType(selectedUri, "text/csv");
intent = Intent.createChooser(intent, "Open folder")
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(electricity_output.this, 0, intent, 0);
createNotificationChannel();
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(electricity_output.this, "1")
.setSmallIcon(R.drawable.logoo)
.setContentTitle("File Downloaded")
.setContentText("Goto your File Manager in " + electricity_output.this.getString(R.string.naam))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(uri)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(electricity_output.this);
notificationManager.notify(0, mBuilder.build());
}
public 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 = "channel";
String description = "Desc";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("1", 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);
}
}
I have an App which can send notifications to the users but since the new PlayStore Updates needs to match targetSdkVersion 26 the notifications dont work anymore with the error toast Failed to post notification on channel “null”. There are some threads about it but i didnt get the solution. Here is my actual FirebaseMessagingService class:
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
What do I need to change to make it working again? It would be good if it also works for devices from sdk 24 up.
Since Android Oreo, you need a Channel to send your notifications.
You can do something like this (not tested) :
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyMgr.createNotificationChannel(notificationChannel);
}
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.
Code:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
You can use this method. Now with latest API versions you need to set channel for notifications.
private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
int icon = R.mipmap.icon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
icon = R.mipmap.icon_transparent;
}
Intent notificationIntent = new Intent(this, CurrentActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.setContentTitle("Service")
.setContentText("Running...");
Notification notification=builder.build();
if(Build.VERSION.SDK_INT>=26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
.setContentTitle("Service")
.setContentText("Running...")
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.build();
}
startForeground(121, notification);
}
Notification is showing on android nougat 7.0 and less but not on Orea 8.0
What should i do?
......................................................................................................................................................
Here is my code:
public class MainActivity extends AppCompatActivity {
Button button;
private final String ChannelId = "Notification";
private final Integer NotificationId = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
}
public void sendNotification (View view) {
Toast.makeText(this, "Notification", Toast.LENGTH_SHORT).show();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, ChannelId);
Intent i = new Intent(MainActivity.this, Main2Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder.setWhen(20000);
mBuilder.setTicker("Ticker");
mBuilder.setContentInfo("Info");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setContentTitle("New notification title");
mBuilder.setContentText("Notification text");
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(2, mBuilder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = "Notification";
CharSequence channelName = "Some Channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
I think you should use notification channel to create the notification
check if Build.VERSION.SDK_INT >= Build.VERSION_CODES.O and then use the channel
here is an example I found on the documentation
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);
}
}
then you use builder to build the notification and then you continue as normal
https://developer.android.com/training/notify-user/channels
This article should be of a good guide to you, according to the new way of implementing Notifications on Android, you need to do that through a Notification Channel
I faced some difficulties implementing this, even though there are so many examples, but here is how it worked for me:
public class RingtonePlayingService extends Service {
NotificationCompat.Builder notificationBuilder;
NotificationManager notificationManager;
NotificationChannel notificationChannel;
String channelId;
CharSequence channelName;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
initNotification();
showNotification();
return START_STICKY;
}
private void initNotification() {
setNotificationChannel();
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
// The methods called for building are following my own needs, change them according to yours
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.alarm)
.setContentTitle("Alarm On!")
.setContentText("Click the notification to dismiss")
.setPriority(NotificationCompat.PRIORITY_HIGH)
// You can add your intents or actions here
.setAutoCancel(true);
}
private void showNotification() {
// You can use a unique alarmRequestCode or just use 1 for testing purposes
notificationManager.notify(alarmRequestCode, notificationBuilder.build());
}
private void setNotificationChannel() {
channelId = "alarm_channel_id";
channelName = "alarm_notification_channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Please note that I removed the if statement since I upgraded my whole gradle to work only with the new versions.
Also I removed all the snippets of code which you might not need so I can make it easier for you to follow, so if the code doesn't really make sense to you remember that you will need to implement this within your own purpose and code!
I hope this will be of a good help :)