Faced with the problem of displaying notifications in android Lollipop. When app is open notifications shows app fine, but when the application is closed they are not displaying. On 4x versions of android everything works properly. Here is a method to display them
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void sendNotification(String body, String title, String badge) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("from_notify", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(badge), intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText(body)
.setPriority(Notification.PRIORITY_HIGH)
.setShowWhen(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
I think this is the problem:
when your app is closed,all app's data will be cleared including the notifications and statics data,so if you want to make notifications alive all the time you have to send it from service(create service class and run it in the background).
try this:
public class YourService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//send your notifications here
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
note that you can send notifications from other classes not just from service class,but you have to run a service in the background because it helps to keep statics data for your app after it is closed.this worked for me.
I hope this will help you.
Related
I am currently trying to implement push notifications for my android app with FCM, However when I send a notification it doesn't appear on the phone. I know for sure that the app received the message since it appears in the logcat, but the notification itself doesn't appear and i'm not sure where I went wrong. I got an error from Glide but I tried again without the LargeIcon and the .notify line outside of the glide line and still nothing appeared. Any help is appreciated :)
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Spannable sb = new SpannableString("Switcheroo");
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.app_icon_waves_round)
.setContentTitle(sb)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Glide.with(getApplicationContext()).asBitmap().load(image).placeholder(R.drawable.music_placeholder).into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
notificationBuilder.setLargeIcon(resource);
notificationManager.notify(0, notificationBuilder.build());
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
LogCat:
D/PAYLOAD: Message data payload: {image=https://is1-ssl.mzstatic.com/image/thumb/WNUBiv2P6YSklHn9eA5nlg/1000x1000bb.jpeg, message=Barbecu sent you his "Run The Jewels" Playlist}
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a #GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
Starting from Android 8.0 (API level 26), notifications won't show unless you provide NotificationChannel as a second argument to the NotificationCompat.Builder constructor.
So, to solve that, create a NotificationChannel for API 26+
// Notification channels are only available in OREO and higher.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel
("PRIMARY_CHANNEL_ID",
"Service",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Description");
notificationManager.createNotificationChannel(notificationChannel);
}
use the channel ID "PRIMARY_CHANNEL_ID" as a second argument to the NotificationCompat.Builder constructor.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "PRIMARY_CHANNEL_ID")
.setSmallIcon(R.mipmap.app_icon_waves_round)
.setContentTitle(sb)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
when you use Glide4 in your app. you have to make class like this.
import android.content.Context;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
#GlideModule
public final class MyAppGlideModule extends AppGlideModule {
#Override
public void applyOptions(Context context, GlideBuilder builder) {
}
}
check this. happy coding!
I am trying to clear notification. But it remains there. Not able to open fragment Activity from notification. Below is my code,
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int sticky;
try {
AndroidLogger.log(5, TAG, "Missed call notification on start");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
NotificationChannel channel = new NotificationChannel("1", "Call Notification", importance);
channel.setDescription("Get alert for missed call");
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Intent notifyIntent = new Intent(this, ViewFragment.class);
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
.setSmallIcon(R.drawable.nexge_logo)
.setContentTitle("Missed Call")
.setContentText(intent.getStringExtra("Number"))
.setContentIntent(pIntent)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX);
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//mNotifyMgr.notify(1, buildNotification);
startForeground(1,buildNotification);
} catch (Exception exception) {
AndroidLogger.error(1, TAG, "Exception while starting service", exception);
}
return START_NOT_STICKY;
}
}
Anybody help me to solve this. Thanks in Advance.
Below is my another question for which I didn't get a proper answer. Help me with that also
About Notification for Missed Call in android
My solution to a similar issue has been changing PendingIntent Flag to PendingIntent.FLAG_ONE_SHOT
From Android documentation:
Flag indicating that this PendingIntent can be used only once. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
and adding notification FLAG_AUTO_CANCEL flag:
mBuilder.flags |= Notification.FLAG_AUTO_CANCEL;
which should make sure the notification will be removed once used.
Edit:
Should call
Notification notification = mBuilder.build();
first, then
notification.flags = Notification.FLAG_AUTO_CANCEL;
Edit2:
Just noticed that you are using the notification for startForeground(). This means that the notification will stay for as long as your Service / Activity is running (this is by default so the user will know that there is a Service / Activity still running).
The notification will stay for as long as your Service / Activity does run as foreground service.
I have a service which displays a notification, the notification works in Android 6.0 and prior but it doesnt show up in 7.0.
Relevant code:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
PendingIntent pendingIntentMain = PendingIntent.getActivity(this, 0, intent_main, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notificationPopup = new Notification.Builder(this).setContentTitle("Alarm is ON!").setContentText("Click here")
.setContentIntent(pendingIntentMain).setAutoCancel(true).setSmallIcon(R.drawable.acd).setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL).build();
notificationManager.notify(0, notificationPopup);
Please follow up this steps and let me know it works or not
Remove 6ya from Battery Optimization:
1.Go to setting battery.
2.Click the Menu on battery page and choose battery optimization.
3.Clicked on Not optimized and go to all apps.
4.On All Apps locate 6ya app and click on it.
5.It will show a pop-up with Optimize and Don't optimize.
6.Click on Don't optimize and hit DONE.
7.6ya Should be located on the not optimized folder .
8.All set - restart the phone.
I'm afraid I have not been able to reproduce the problem you're seeing.
In my tests, this code creates and displays the notification successfully on Android 5.1, 6.0, 7.0 and 7.1.1:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
}
}
MyService.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// create and display a notification
Intent intent_main = new Intent(this, MainActivity.class);
PendingIntent pendingIntentMain = PendingIntent.getActivity(this, 0, intent_main, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notificationPopup = new Notification.Builder(this)
.setContentTitle("Alarm is ON!")
.setContentText("Click here")
.setContentIntent(pendingIntentMain)
.setAutoCancel(true)
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationPopup);
return super.onStartCommand(intent, flags, startId);
}
}
I have implemented push notifications using Azure's Notification Hub. I have noticed that they only have three override methods when extending NotificationHandler:
public void onReceive(Context context, Bundle bundle)
public void onUnregistered(Context context, String gcmRegistrationId)
public void onRegistered(Context context, String gcmRegistrationId)
Most push notification services have an onPushOpen() or onOpen() callback method which is called when a user presses on the push notification they received. How do I know when someone has clicked on the received push notification? I am experimenting with the demo. Everything works minus the concern I have said.
Link: https://github.com/Azure/azure-notificationhubs-samples/blob/master/Android/GetStartedFirebase/app/src/main/java/com/example/microsoft/getstartednh/MyHandler.java
public class MyHandler extends NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("message");
sendNotification(nhMessage);
if (MainActivity.isVisible) {
MainActivity.mainActivity.ToastNotify(nhMessage);
}
}
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSound(defaultSoundUri)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
For anyone else trying to figure this out, it is actually pretty simple. In the sendNotification() method, whatever information you want to keep track of when the push notification is opened add it as extras to your intent. For example.
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// seeking to do something specific when notification is opened if flag is set
intent.putExtra("onPushOpen", "performSomeAction");
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSound(defaultSoundUri)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
Now that you have done this. In onResume() check for that information. It will be empty (null) when push notification is not invoked, otherwise, it will have your information.
Bundle b = getIntent().getExtras();
// now retrieve what you want from the bundle.
I am working on a small project that involves a web interface that can send information to my android app which will display such information as Push Notifications.
But here is the thing, I am a bit confused with how to do that. As in what step will i have to take.
So I have a web interface in HTML which has a Textfield for notification Title, Content, and a submit button. I want it that when the user clicks the Submit button, the webpage will send the text that s in the Title and Content fields to my android app and then the app will just display them as push notifications.
So far on the app i have it that when you click a button on your device then it just shows a notification on the Actionbar. This is great for testing but It would be better that you can just compose your notification through a web interface.
My test Push Notification code for the app:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
// TODO: Make this accessible to exterior projects, such as web interface.
Notification notification = new Notification.Builder(MainActivity.this)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nManager.notify(0, notification);
}
});
If anyone could be so kind to give me a hand, it would be much appreciated.
You are right, so far so good with the notification bar, now what you need is a notification service, and google has something like that for us...
how does this works??
Take a look at the image below,
you need to register your android app in the google service, and your web interface will need an id, so everytime you want to push something to the android, your web interface instead will push it to the google server with the Id of the app, then google (no matter how) will localize your app, and even if its not running, they will get the notification,
behind the scenes there is a couple of thing that you must do, bu nothing like launching rockets from the NASA.
I will suggest to take a look to some tutorials
in order to start with the registration of your app, get the api key etc etc..
Here is a great source in github which shows how you can add push notification service in your android app
github.com/rana01645/android-push-notification
Firstly read the full documentation
How to add push notification in android application from android studio – Android developer (part – 1 Connect with firebase ) ~ http://androidrace.com/2016/12/08/how-to-add-push-notification-in-android-application-from-android-studio-android-developer-part-1-connect-with-firebase/
How to add push notification in android application from android studio – Android developer (part – 2 Working with server) ~http://androidrace.com/2017/01/05/how-to-add-push-notification-in-android-application-from-android-studio-android-developer-part-2-working-with-server/
Then you can able to send push notification from your server using html
public class Uyarilar extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
Date currentTime = Calendar.getInstance().getTime();
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.presta)
.setContentTitle("Saat 9:00")
.setContentText("Mesai saatiniz başlamıştır Lütfen harakete geçiniz!");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
and call
private void setNotification() {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, 9);
calSet.set(Calendar.MINUTE, 00);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if (calSet.compareTo(calNow) <= 0) {
calSet.add(Calendar.DATE, 1);
}
Date currentTime = Calendar.getInstance().getTime();
Intent intent = new Intent(getBaseContext(), Uyarilar.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);
}
and
onCreate
setNotification();
this method to push notification
public void testMessage (String message , Intent intent){
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "some_channel_id";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder =
new android.support.v4.app.NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setBadgeIconType(android.support.v4.app.NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
assert notificationManager != null;
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}