We have created an chat app with notifications using FCM my code is correct my device is getting the push notification data as well but some Chinese manufactured device like vivo, oppo, one plus, xiaomi are not allowing the notification to show unless i add app in protected app list of respective manufacturer. is their any solution for this.
https://hackernoon.com/notifications-in-android-are-horribly-broken-b8dbec63f48a
https://github.community/t5/Project-Development-Help-and/Firebase-Push-Notification-not-receiving-on-some-android-devices/td-p/5489
private NotificationManagerCompat notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("test","call");
notificationManager = NotificationManagerCompat.from(this);
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
private void sendNotification(String title, String msg) {
Intent resultIntent = new Intent(this, ActivitySplashScreen.class);
String channelId = getString(R.string.chc);
String channelName = "Message Notification";
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(99, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(msg)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager manager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
notificationManager.notify(10, notification);
}
I can confirm that this implementation works well with One Plus and Xiaomi devices (we have plenty of users using our app from this devices, and no crashes or issues are created from them regarding FCM Notifications).
Cannot confirm anything for Vivo or Oppo (so far, we do know we don't have users using this kind of devices).
The most important thing is that the notification feature is well implemented if regarding the app is either in foreground or background. If someone wants to do a zoom on this matter, this article explains it on a easy way.
Now, the code I use for FCM implementation in Android:
//MyMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "Firebase Msg";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
final LocalNotification localNotification = new LocalNotification();
//data --> entityId - entityType - pushNotificationType
// Check if message contains a data payload.
if (data.size() > 0) {
localNotification.setEntityId(data.get("entityId"));
localNotification.setEntityType(data.get("entityType"));
localNotification.setPushNotificationType(data.get("pushNotificationType"));
localNotification.setTitle(data.get("title"));
localNotification.setBody(data.get("body"));
localNotification.setIcon(data.get("icon"));
localNotification.setDate(new Date().getTime());
localNotification.setRead(false);
}
if (localNotification.getEntityId() != null) {
LocalNotification notificationRetrieved = FirebaseNotificationsHelper.insertLocalNotification(localNotification);
FirebaseNotificationsHelper.createNotificationInStatus(notificationRetrieved);
}
}
}
//Create notification status
static void createNotificationInStatus(LocalNotification localNotification) {
String notificationChannelId = App.getContext().getString(R.string.default_notification_channel_id);
String notificationChannelName = App.getContext().getString(R.string.default_notification_channel_name);
String notificationChannelDescription = App.getContext().getString(R.string.default_notification_channel_description);
NotificationCompat.Builder notificationBuilder;
NotificationCompat.Builder notificationBuilderPublicVersion;
notificationBuilder = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilderPublicVersion = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE | NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_SOUND)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_stat_push_notif)
.setTicker(localNotification.getTitle())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(localNotification.getTitle())
.setContentText(localNotification.getBody())
.setStyle(new NotificationCompat.BigTextStyle().bigText(localNotification.getBody()))
.setPublicVersion(notificationBuilderPublicVersion.setSmallIcon(R.drawable.ic_stat_push_notif).setContentTitle(localNotification.getTitle()).
setWhen(System.currentTimeMillis()).setContentText(localNotification.getBody()).build())
.setGroup(NOTIFICATION_GROUP)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setAutoCancel(true);
int notificationId = SharedPreferencesUtils.getInstance(App.getContext()).getIntValue(PREF_KEY_NOTIFICATION_ID, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, notificationChannelName, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription(notificationChannelDescription);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
/* Kitkat and previous versions don't show notifications using NotificationManagerCompat */
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.getContext());
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
notificationId++;
SharedPreferencesUtils.getInstance(App.getContext()).setValue(PREF_KEY_NOTIFICATION_ID, notificationId);
}
I donot think that there is a general solution for this since your app is based on google-FCM that means that the android device regularly comunicates with google-internet-services.
As far as i know google-FCM is blocked (= not reachable) in china
Related
After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.
In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.
#TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
// Safe call, handled by compat lib.
val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build()
startForeground(101, notification)
}
Error message:
11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
Process: $PACKAGE_NAME, PID: 24704
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation
After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.
private fun startForeground() {
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
#RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE)
chan.lightColor = Color.BLUE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.
Update:
Also don't forget to add the foreground permission as required Android P:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Java Solution (Android 9.0, API 28)
In your Service class, add this:
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
UPDATE: ANDROID 9.0 PIE (API 28)
Add this permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer
public Notification getNotification() {
String channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
Notification notification = mBuilder
.setPriority(PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
return notification;
}
#NonNull
#TargetApi(26)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "snap map fake location ";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "snap map channel";
}
For android, P don't forget to include this permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Works properly on Andorid 8.1:
Updated sample (without any deprecated code):
public NotificationBattery(Context context) {
this.mCtx = context;
mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.notification_title_battery))
.setSmallIcon(R.drawable.ic_launcher)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setChannelId(CHANNEL_ID)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setWhen(System.currentTimeMillis() + 500)
.setGroup(GROUP)
.setOngoing(true);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);
initBatteryNotificationIntent();
mBuilder.setContent(mRemoteViews);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setSound(null, null);
mNotificationManager.createNotificationChannel(channel);
}
} else {
mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
}
}
Old snipped (it's a different app - not related to the code above):
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.d(TAG, "onStartCommand");
String CHANNEL_ONE_ID = "com.kjtech.app.N1";
String CHANNEL_ONE_NAME = "Channel One";
NotificationChannel notificationChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle(getString(R.string.obd_service_notification_title))
.setContentText(getString(R.string.service_notification_content))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(START_FOREGROUND_ID, notification);
return START_STICKY;
}
In my case, it's because we tried to post a notification without specifying the NotificationChannel:
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";
public void initChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
}
}
The best place to put above code is in onCreate() method in the Application class, so that we just need to declare it once for all:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
initChannel();
}
}
After we set this up, we can use notification with the channelId we just specified:
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
.setContentIntent(pi)
.setWhen(System.currentTimeMillis())
.setContentTitle("VirtualBox.exe")
.setContentText("Download completed")
.setSmallIcon(R.mipmap.ic_launcher);
Then, we can use it to post a notification:
int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());
If you want to use it as foreground service's notification:
startForeground(notifId, builder.build());
Thanks to #CopsOnRoad, his solution was a big help but only works for SDK
26 and higher. My app targets 24 and higher.
To keep Android Studio from complaining you need a conditional directly around the notification. It is not smart enough to know the code is in a method conditional to VERSION_CODE.O.
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(AppSpecific.SMALL_ICON)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
}
This worked for me. In my service class, I created the notification channel for android 8.1 as below:
public class Service extends Service {
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
} else {
Notification notification = new Notification();
startForeground(1, notification);
}
}
}
Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei
I had the same issue. The problem occurred when I used same channel id and notification id for two apps. So try with a unique notification id and channel id.
this maybe old but, incase someone had the same situation as I did.
for some reason, on Android 11 OnePlus Nord
Notification.Builder().Build()
crashes,
NotificationCompat.Builder().Build()
works fine.
Consider migrating to androidx.core.app.NotificationCompat.
If you're working with VPN library, these code will be help, I placed this inside onCreate(savedInstanceState: Bundle?)
NotificationChannelManager.createNotificationChannelIfNeeded(
activity,
channelName = "Chanel Name",
channelDescription = "Channel description"
)
Here is my solution
private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";
private void startForeground() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), CHANNEL_ID);
Notification notification;
notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Send SMS gateway is running background")
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.build();
NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
//All notifications should go through NotificationChannel on Android 26 & above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
Hope it will help :)
I am making MQTT client app using paho MQTT client dependency.
Implementing code in a Background Service. and everything works well except the Notification isn't working!
Service code snippet is here:
My Codes occurs inside the TimeDisplayTimerTask inner-class.
This code located at the callback function :
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
mIntent = new Intent(getApplicationContext(), MainActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);
createNotificationChannel();
Toast.makeText(getApplicationContext(),"A message received : "+ new String(message.getPayload()),Toast.LENGTH_SHORT).show();
vibrator.vibrate(500);
myRingtone.play();
mBuilder .setContentTitle("Message received at : " + mTopic)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentText("Message : "+ new String(message.getPayload()));
mNotificationManager.notify(0, mBuilder.build());
}
And this code creates a notification channel (as Google developers guide mentioned to write):
Posted with help of this answer.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String chanel_id = "3000";
CharSequence name = "Mqtt message";
String description = "Message arrived";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
mNotificationManager = getSystemService(NotificationManager.class);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(getApplicationContext(), chanel_id);
}
else
{
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
}
}
When it receives a message, A toast message appears holding the message.
But it doesn't push notification.
Checked Apps and Notifications, All notifications are allowed.
SOLVED :
the setter method .setSmallIcon must be called to successfully build a notification.
Which was not important to me.
I am working on an application which sends device to device push notification. I have created a custom notification layout which has a heading, message and two buttons (Accept and Reject). When device B receives a notification from Device A, for some phones it works perfectly, but in some phones the notification tray fails to display the title, message and buttons. It just shows a blank notification tray. Its not an error, but the custom layout doesn't load for some phones. It works perfectly in Moto G5s plus (Android 7.1.1), but doesn't work for RedMi Note 5 Pro, same API level (Android 7.1.1). Can anyone help me with this?
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> remoteMessageData = remoteMessage.getData();
String remoteMessageType = remoteMessageData.get("type");
String message = remoteMessageData.get("message") + ". Please Confirm?";
String profilePhoto = remoteMessageData.get("profile_photo");
String notificationUID = remoteMessageData.get("notification_uid");
String userUID = remoteMessageData.get("user_uid");
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_custom_notification);
remoteViews.setTextViewText(R.id.textNotificationMessage, message);
remoteViews.setImageViewBitmap(R.id.eIntercomProfilePic, getBitmapFromURL(profilePhoto));
Notification notification = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.namma_apartment_notification)
.setAutoCancel(true)
.setCustomBigContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND))
.setPriority(PRIORITY_DEFAULT)
.build();
int mNotificationID = (int) System.currentTimeMillis();
Intent acceptButtonIntent = new Intent("accept_button_clicked");
acceptButtonIntent.putExtra("Notification_Id", mNotificationID);
acceptButtonIntent.putExtra("Notification_UID", notificationUID);
acceptButtonIntent.putExtra("User_UID", userUID);
PendingIntent acceptPendingIntent = PendingIntent.getBroadcast(this, 123, acceptButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonAccept, acceptPendingIntent);
Intent rejectButtonIntent = new Intent("reject_button_clicked");
rejectButtonIntent.putExtra("Notification_UID", notificationUID);
rejectButtonIntent.putExtra("Notification_Id", mNotificationID);
rejectButtonIntent.putExtra("User_UID", userUID);
PendingIntent rejectPendingIntent = PendingIntent.getBroadcast(this, 123, rejectButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonReject, rejectPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/*To support Android Oreo Devices and higher*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
getString(R.string.default_notification_channel_id), "Namma Apartments Channel", NotificationManager.IMPORTANCE_HIGH);
Objects.requireNonNull(notificationManager).createNotificationChannel(mChannel);
}
}
i think you talking about Oreo or above version. Oreo can not support notification for notification you need to create channel for that like below :
private void sendMyNotification(String message,String title) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel notificationChannel=new NotificationChannel("my_notification","n_channel",NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("description");
notificationChannel.setName("Channel Name");
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.listlogo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.tlogo))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_MAX)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));
//.setProgress(100,50,false);
notificationManager.notify(0, notificationBuilder.build());
}
After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.
In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.
#TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
// Safe call, handled by compat lib.
val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build()
startForeground(101, notification)
}
Error message:
11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
Process: $PACKAGE_NAME, PID: 24704
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation
After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.
private fun startForeground() {
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
#RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE)
chan.lightColor = Color.BLUE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.
Update:
Also don't forget to add the foreground permission as required Android P:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Java Solution (Android 9.0, API 28)
In your Service class, add this:
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
UPDATE: ANDROID 9.0 PIE (API 28)
Add this permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer
public Notification getNotification() {
String channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
Notification notification = mBuilder
.setPriority(PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
return notification;
}
#NonNull
#TargetApi(26)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "snap map fake location ";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "snap map channel";
}
For android, P don't forget to include this permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Works properly on Andorid 8.1:
Updated sample (without any deprecated code):
public NotificationBattery(Context context) {
this.mCtx = context;
mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.notification_title_battery))
.setSmallIcon(R.drawable.ic_launcher)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setChannelId(CHANNEL_ID)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setWhen(System.currentTimeMillis() + 500)
.setGroup(GROUP)
.setOngoing(true);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);
initBatteryNotificationIntent();
mBuilder.setContent(mRemoteViews);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setSound(null, null);
mNotificationManager.createNotificationChannel(channel);
}
} else {
mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
}
}
Old snipped (it's a different app - not related to the code above):
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.d(TAG, "onStartCommand");
String CHANNEL_ONE_ID = "com.kjtech.app.N1";
String CHANNEL_ONE_NAME = "Channel One";
NotificationChannel notificationChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle(getString(R.string.obd_service_notification_title))
.setContentText(getString(R.string.service_notification_content))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(START_FOREGROUND_ID, notification);
return START_STICKY;
}
In my case, it's because we tried to post a notification without specifying the NotificationChannel:
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";
public void initChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
}
}
The best place to put above code is in onCreate() method in the Application class, so that we just need to declare it once for all:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
initChannel();
}
}
After we set this up, we can use notification with the channelId we just specified:
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
.setContentIntent(pi)
.setWhen(System.currentTimeMillis())
.setContentTitle("VirtualBox.exe")
.setContentText("Download completed")
.setSmallIcon(R.mipmap.ic_launcher);
Then, we can use it to post a notification:
int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());
If you want to use it as foreground service's notification:
startForeground(notifId, builder.build());
Thanks to #CopsOnRoad, his solution was a big help but only works for SDK
26 and higher. My app targets 24 and higher.
To keep Android Studio from complaining you need a conditional directly around the notification. It is not smart enough to know the code is in a method conditional to VERSION_CODE.O.
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(AppSpecific.SMALL_ICON)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
}
This worked for me. In my service class, I created the notification channel for android 8.1 as below:
public class Service extends Service {
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
} else {
Notification notification = new Notification();
startForeground(1, notification);
}
}
}
Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei
I had the same issue. The problem occurred when I used same channel id and notification id for two apps. So try with a unique notification id and channel id.
this maybe old but, incase someone had the same situation as I did.
for some reason, on Android 11 OnePlus Nord
Notification.Builder().Build()
crashes,
NotificationCompat.Builder().Build()
works fine.
Consider migrating to androidx.core.app.NotificationCompat.
If you're working with VPN library, these code will be help, I placed this inside onCreate(savedInstanceState: Bundle?)
NotificationChannelManager.createNotificationChannelIfNeeded(
activity,
channelName = "Chanel Name",
channelDescription = "Channel description"
)
Here is my solution
private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";
private void startForeground() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), CHANNEL_ID);
Notification notification;
notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Send SMS gateway is running background")
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.build();
NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
//All notifications should go through NotificationChannel on Android 26 & above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
Hope it will help :)
I recently updated my app to API 26, and notifications are no longer working, without even changing the code.
val notification = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Title")
.setContentText("Text")
.build()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notification)
Why isn't it working? Was there some change to the API that I'm not aware of?
From the documentation:
Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.
(emphasis added)
You do not seem to be associating this Notification with a channel.
Here i post some quick solution
public void notification(String title, String message, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = createID();
String channelId = "channel-id";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.app_logo)//R.mipmap.ic_launcher
.setContentTitle(title)
.setContentText(message)
.setVibrate(new long[]{100, 250})
.setLights(Color.YELLOW, 500, 5000)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(new Intent(context, MainAcivity.class));
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
public int createID() {
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.FRENCH).format(now));
return id;
}