Unable to receive local notifications Android - java

I'm new to Android programming and I'm trying to build my first app. Right now I want to send local notifications. Unfortunately I cannot receive notifications on devices running API 28 and above. I know there is a change in the way notifications are sent since Oreo and I have included code that creates the channel. It seems like if I run the app on a simulator with a lower API (e.g. 19) the notification is received. Also if I copy my code into a new project I receive the notifications, even on a simulator running Android Oreo. What settings in the project could cause notifications not to be received on Android Oreo? (There are no errors in Logcat)
My code for sending the notifications:
public static final String CHANNEL_1_ID = "channel1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannels();
}
public void setNotif(View view) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hey")
.setContentText("world")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, notification);
}
private void createNotificationChannels() {
// if higher than android oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("This is channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
The setNotif method is called by a tap of a button. Again, I'm new to Android programming so any advice would be helpful. Maybe even a different way in which I could diagnose the issue. Thank you!

Add this check in your setNotif() method:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
notificationManager.createNotificationChannel(getNotificationChannel(context));
setNotif() method will be changed like this :
public void setNotif(View view) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hey")
.setContentText("world")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notificationManager.createNotificationChannel(getNotificationChannel(context));
notificationManager.notify(1, notification);
}
And getNotificationChannel() method will look like this:
private static NotificationChannel getNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
return null;
CharSequence name = context.getString(R.string.app_name);// The user-visible name of the channel.
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(BuildConfig.APPLICATION_ID, name, importance);
notificationChannel.setShowBadge(true);
return notificationChannel;
}

Related

Notification doesn't work - Android Studio

So I am a beginner and I was following one tutorial on how to make notification in Android Studio. This app should make a notification when you press a button, but instead of making notification it shows up a Developer Warning
Error:
No Channel found for pkg=com.example.myapplication, channelId=My notification, id=1, tag=null, opPkg=com.example.myapplication, callingUid=10153, userId=0, incomingUserId=0, notificationUid=10153, notification=Notification(channel=My notification shortcut=null contentView=null vibrate=null sound=null defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE)
Code(Java):
public void onClick(View v) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,"My notification");
builder.setContentTitle("My Title");
builder.setContentText("Test");
builder.setSmallIcon(R.drawable.ic_launcher_background);
builder.setAutoCancel(true);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(MainActivity.this);
managerCompat.notify(null,0, builder.build());
}
});
Do you know how to fix this?
Starting with Android 8.0 (API level 26), notifications require a notification channel.
This is a category which you create and assign to your notifications. Having multiple notification channels per app, allows users to better manage which kind of notifications they want to receive from an app.
To achieve this, you need to create a notification channel as stated in the example in the Android docs:
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);
}
}
Source
CHANNEL_ID can be any integer number which doesn't change during the lifetime of your app. It is OK if you make it a static final int.
Once you created the channel, you can specify the same CHANNEL_ID when creating notifications:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Source
private Notification getNotification() {
Intent notificationIntent = new Intent(this, VideoExportActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationChannel notificationChannel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel("CHANNEL_ID", "Alarm Time....", NotificationManager.IMPORTANCE_DEFAULT);
}
NotificationManager notificationManager = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notificationManager = getSystemService(NotificationManager.class);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(notificationChannel);
}
return new NotificationCompat.Builder(this, "CHANNEL_ID")
.setContentTitle("Title")
.setContentText("Your Message")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
}
Notification notification = getNotification();

Why my notification does not work in android TV emulator?

I am trying to implement an android TV application by using android studio and TV emulator.
I call the following code blocks at the onCreate function of the main activity. It is running for android mobile devices but not working on the Android TV emulator.
String channel_name = "myChannel";
String channel_description = "mySChannel";
String CHANNEL_ID = "idididf";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_my_icon)
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = channel_name;
String description = 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.createNotificationChannel(channel);
}
notificationManager.notify(12312, builder.build()); // 0 is the request code, it should be unique id
Any idea?
With very few exceptions, notifications are not shown on Android TV.

How to make notification for Wear Os?

I have done notification on Android before and I haven't any problems with it. But, when I have tried to make notification by example for Wear OS I have an error. It says that: "Field to post a notification on channel: "my_channel_01""
public class MainActivity extends WearableActivity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
int notificationId = 001;
// The channel ID of the notification.
String id = "my_channel_01";
// Build intent for notification content
Intent viewIntent = new Intent(this, MainActivity.class);
viewIntent.putExtra("EXTRA_EVENT_ID", 1);
PendingIntent viewPendingIntent =
PendingIntent.getActivity(this, 0, viewIntent, 0);
createNotificationChannel();
// Notification channel ID is ignored for Android 7.1.1
// (API level 25) and lower.
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, id)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle("Hello World")
.setContentText("eventLocation")
.setContentIntent(viewPendingIntent);
// Get an instance of the NotificationManager service
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
// Issue the notification with notification manager.
notificationManager.notify(notificationId, notificationBuilder.build());
// Enables Always-on
setAmbientEnabled();
}
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 = "Test";
String description = "Notification for Wear OS";
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 used SDK 28
In createNotificationChannel method, you need to set up id as id onCreate method like this:
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) {
String id = "my_channel_01";
CharSequence name = "Test";
String description = "Notification for Wear OS";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(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);
}

Firebase Messaging Service Not Working On Older Android

Recently I`ve migrated GCM to FCM and after some struggle, I've managed to make everything work with the help of this great community.
Now when I tested notifications on older version of Android ( Nougat) it doesn't work, app just crash, I've found out that its something related to versions as older ones doesn't support channel managers.
I've found few solutions on StackOverflow but I haven't find a suitable one for my problem so I was hoping someone could toss me a hint or solution.
I appreciate all the answers and help.
public class MessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Message";
public MessagingService() {
super();
}
#TargetApi(Build.VERSION_CODES.O)
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String message = remoteMessage.getData().get("team");
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
String CHANNEL_ID="channel";
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"channel",NotificationManager.IMPORTANCE_HIGH);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
.setContentText(message)
// .setContentTitle(title)
.setSound(defaultSound)
.setContentIntent(pendingIntent)
.setChannelId(CHANNEL_ID)
.setSmallIcon(android.R.drawable.sym_action_chat)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.build();
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(1,notification);
}
}
I think it is crashing because Notification Channels dose not supported in android versions older than Oreo.
So you can fix it by adding an android sdk version checker and set notification channel just when app is running on android Oreo or higher:
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);
Notification notification=new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setContentText(message)
.setSound(defaultSound)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.sym_action_chat)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.build();
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID="channel";
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"channel",NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(1, notification);
Also notice that I used NotificationCompat.Builder instead of Notification.Builder and removed .setChannel() because it is not necessary when we are passing the channel id in builder constructor.

Android 8.1 notifications showing but not making any sounds

I have a service which runs in foreground with, among other things, a stopwatch. When the service starts the notification appears, and when it ends I update it with sound and some text that indicates that it's finished. The problem is that this works well until api 25, but for 26 and 27 it updates the notification alright, but makes no sound. Here's the relevant code:
The creation of the notification inside the service:
mBuilder = new NotificationCompat.Builder(context, "Main")
.setSmallIcon(R.drawable.ic_notification_temp)
.setContentTitle(step.getDescription())
.setContentText(getString(R.string.notification_text))
.setVisibility(VISIBILITY_PUBLIC)
.setOngoing(true);
.setDeleteIntent(deletePendingIntent);
.setContentIntent(contentPendingIntent);
.addAction(R.drawable.ic_stop_red_24dp, getString(R.string.cancel),finnishPendingIntent);
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
The update to the notification builder when the "work" is finished:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setVibrate(new long[]{0, 300, 0, 400, 0, 500});
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mBuilder.setContentText(getString(R.string.notification_finished_text));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setChannelId("Sound");
mBuilder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
mNotificationManager.notify(mId, mBuilder.build());
The 2 channels created just for api 26 or up on app start:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the normal NotificationChannel
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel("Main", name, importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
// Create theNotificationChannel with sound
importance = NotificationManager.IMPORTANCE_HIGH;
name = getString(R.string.notification_channel_sound);
NotificationChannel sound = new NotificationChannel("Sound", name, importance);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
notificationManager.createNotificationChannel(sound);
}
And that's where I'm at now. I've tried to not use setsound() as I've read that the notification should just play the default sound with the appropriate importance (and of course I've even uninstalled the app between tries to correctly update the channel settings) but nothing seems to work for api 26 and I just don't know what I'm doing wrong.
I had the exact same problems with most of my emulator AVDs. The following fixed it for me:
start the affected AVD
long press the AVD's power button
restart the AVD
Afterwards it should work again.
Tried to reproduce your issue and finished with created MVP, maybe this will help you to find the problem:
Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View btn = findViewById(R.id.clickMe);
btn.setTag(NotifService.CHANNEL_ID_MAIN);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String channelId = (String) v.getTag();
Intent intent = new Intent(v.getContext(), NotifService.class);
intent.putExtra(NotifService.TAG, channelId);
if (channelId.equals(NotifService.CHANNEL_ID_MAIN)) {
v.setTag(NotifService.CHANNEL_ID_SOUND);
} else {
v.setTag(NotifService.CHANNEL_ID_MAIN);
}
v.getContext().startService(intent);
}
});
}
}
Service:
public class NotifService extends IntentService {
public static final String TAG = "NotificationService";
public static final String CHANNEL_ID_MAIN = "Main";
public static final String CHANNEL_ID_SOUND = "Sound";
public static final int NOTIFICATION_ID = 123;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public NotifService() {
super(TAG);//Used to name the worker thread, important only for debugging.
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_MAIN, "Channel Main", NotificationManager.IMPORTANCE_LOW);
NotificationChannel sound = new NotificationChannel(CHANNEL_ID_SOUND, "Channel Sound", NotificationManager.IMPORTANCE_HIGH);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
notificationManager.createNotificationChannel(sound);
}
}
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
String channelId = intent.getStringExtra(TAG);
showNotification(channelId);
}
private void showNotification(String channelId) {
boolean inProgress = channelId.equals(CHANNEL_ID_MAIN);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Work")
.setContentText(inProgress ? "InProgress" : "Finished")
.setOngoing(inProgress)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(!inProgress);
if (!inProgress) {
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
}
This works good on my device 8.1 and Emulator 8.1 (without sound on first click for first notification and with vibration + sound on second click for work complete notification).

Categories

Resources