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());
}
Related
I've followed every single guide on setting up notifications and notification channel. It does work but it's very inconsistent. Sometimes I can see the notification appearing but most of the time, it never shows up. Yet in the notification history, it shows that it got triggered.
This is so frustrating. I'm trying to develop an custom alarm clock app but what use is it when the damn thing doesn't notify the user
public static void CreateNotificationChannel(Context context){
Log.d(TAG, "Creating Notification Channel");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
Log.d(TAG, "Created Notification Channel");
}
public static void CreateNotification(Context context, String title, String contentText){
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title)
.setContentText(contentText)
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(4444, builder.build());
}
Below is code retrieving alarms from Sqlite and then setting it up with intent and alarm manager
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(cursor1.getString(3)));
calendar.set(Calendar.MINUTE, Integer.parseInt(cursor1.getString(4)));
calendar.set(Calendar.SECOND, Integer.parseInt(cursor1.getString(5)));
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
intent.putExtra("requestCode", cursor1.getString(0));
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), Integer.parseInt(cursor1.getString(0)), intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
What exactly is wrong with this? And why it refuses to show a notification while the app is in the foreground or locked and yet, it still appears in the Notification History??
How can I switch all these settings on programmatically?
I noticed when you install WhatsApp they are all switched on in the beginning(look at the image below).
But I can not find a way to turn them on programmatically.
Here is how I send notifications:
private void sendNotification(Intent intent){
Context context = NotificationService.this;
//open the activity after the notification is clicked
Intent intent1 = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent1, 0);
Notification.Builder builder = new Notification.Builder(context)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.drawable.ic_add)
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//These are necessary for the notification to pop up
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
builder.setPriority(Notification.PRIORITY_MAX);
builder.setSound(alarmSound);
builder.setLights(Color.BLUE, 500, 500);
}
//after android O we must use notification channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Reminder to remind to review your notes",
NotificationManager.IMPORTANCE_HIGH);
if(alarmSound != null){
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
channel.setSound(alarmSound,att);
}
channel.setLightColor(Color.BLUE);
channel.enableVibration(true);
channel.setDescription("Hello Dear friends"); //this is to test what this is
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setVibrationPattern(new long[]{300, 300, 300});
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
I also added this permission to manifest:
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
Update:
Using this code on the emulator, I get the heads-up notification. But on my Xiaomi device, there is no heads-up notification. It just appears on the status bar. If I manually turn on the floating notification (which you can see in the photo) then I will get heads-up notification. But they are switched off by default. When you install Whatsapp they are all switched on.
Is that a kind of privilege for Whatsapp as it is famout? or is there a way to do it?
By default, when you install a app, the system register's default notification channel (on low priority) that doesn't support head up notification by default, it's turned off. You can't control that.
But what you can do it create your own notification channel with highest priority and then register it on app run once.
After that just pass the channel Id with your notification builder so that system shows the head's up notification which you want.
More information can be found here https://developer.android.com/training/notify-user/channels
I have tried for this but unable to set these settings programmatically. Instead of this I have used following method to open notification settings screen to enable notification sounds/vibration.
private void openNotificationSettingsForApp(String channelId) {
// Links to this app's notification settings.
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && channelId!=null){
intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID,channelId);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
}
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
startActivity(intent);
}
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.
This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I'm trying to pop up a notification when my alarm manager fires my onReceive() method. This is what I have done
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire(10000);
startNotification(context);
wl.release();
}
public void setAlarm(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(Activity, "MainActivity.class");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
assert am != null;
am.set(AlarmManager.RTC_WAKEUP, 60000, pi);
}
private void startNotification(Context context){
// Sets an ID for the notification
int mNotificationId = 001;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// Build Notification , setOngoing keeps the notification always in status bar
mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("RandomTitle")
.setContentText("RandomText")
.setOngoing(true);
// Create pending intent, mention the Activity which needs to be
//triggered when user clicks on notification(StopScript.class in this case)
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("extra","Extra Notificacion");
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
// context.startActivity(notificationIntent);
mBuilder.setContentIntent(contentIntent);
// Gets an instance of the NotificationManager service
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Android Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
// Builds the notification and issues it.
notificationManager.notify(mNotificationId, mBuilder.build());
}
Im really confused why this notification is not showing, I have tested my alarm and it triggers after 1 minute of beign created, but the notification is still not showing.
Any ideas?
thanks
From Android developer:
When you target Android 8.0 (API level 26), you must implement one or
more notification channels. If your targetSdkVersion is set to 25 or
lower, when your app runs on Android 8.0 (API level 26) or higher, it
behaves the same as it would on devices running Android 7.1 (API level
25) or lower.
Because your targetSdkVersion is 28, so you must add channelId in the Builder constructor too.
Change your code to:
// Build Notification , setOngoing keeps the notification always in status bar
mBuilder = new NotificationCompat.Builder(context, "notify_001") // Add channel ID to the constructor.
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("RandomTitle")
.setContentText("RandomText")
.setOngoing(true);
As per Android Developers Documentation :
NotificationCompat.Builder
NotificationCompat.Builder (Context context)
This constructor was deprecated in API level 26.1.0. use
NotificationCompat.Builder(Context, String) instead. All posted
Notifications must pecify a NotificationChannel Id.
Reference here
Edit:
Try the following :
Leave the NotificationCompat.Builder as it is now (with a string
representing NotificationChannel) .
Comment out your if block where you create a notification channel
Replace your NotificationManager with NotificationManagerCompat as the following :
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(mNotificationId, mBuilder.build());
I'm new to android. And to show notification on android phones I got this below code
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /*Request code*/ , intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mytune_default)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m /*ID of notification*/ , notificationBuilder.build());
But the thing is I just want that notification unread count on code appview on system, but dont want other things loke message, title etc that appear on notification tray of system. How come this be acheived>
It's not possible to replace launcher icon with widget. You can say to user to place your widget on the home screen, but not in application list. Users must do that in their own. Nevertheless, it's iOs pattern. It's not good idea to bring iOS design elements to android. Android have great notification bar, where user expect to see notification from your app. Android users don't expect to see it over the icon.