Notification after a time - java

I want to add a Notificationmanager which should start after some milliseconds.
Everything is running, but still I don't knoe how to add the time that the notification comes after some weeks for example?
public void test(){
int icon = R.drawable.ic_launcher;
CharSequence ticker ="ticker";
long showAt =System.currentTimeMillis();
Notification notification = new Notification(icon, ticker, showAt);activity/intent
CharSequence notificationTitle = "test";
CharSequence notificationMessage = "Test1";
Intent intent = new Intent(this, Activity.class);
PendingIntent objPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Context ctx = getApplicationContext();
notification.setLatestEventInfo(ctx, notificationTitle, notificationMessage, objPendingIntent);
final int notificationIdentifier = 101; //an unique number set by developer to identify a notification, using this notification can be updated/replaced
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationIdentifier, notification);
// ...
}

You need to use Alarm manager with notification for repeating your notification after a regular time interval. Check AlarmManagerNotificationManagerTutorial , Android AlarmManager tutorial and Multiple Notifications Using AlarmManager . There are many tutorials out there. Hope this helps.

Related

Setting multiple alarms in Android Studio with an alarmmanager causes problems

I currently have a small project running in Android Studio that I need help with. I want to include a reminder function with notifications.
I have a total of 4 time pickers for each of which I want to set an alarm at the corresponding selected time.
With my current code the planned feature works only halfway, with the following problem:
If I select one time, then I sometimes get a notification at this time as desired. However, not always on time. Most of the time the alert doesn't appear and if it does, then half a minute to a minute later. And if I set all 4 alarms, in the best case I get a notification at the last selected time. In the worst case nothing happens.
But all I want is to get daily notifications at the selected 4 times.
About my code, I use an alarm manager which I call 4 times for the 4 alarms. I also use a broadcast receiver in which the notification is triggered. And I use a different RequestCode for each PendingIntent.
I really searched all relevant posts on SO, but not one of them worked for me. Maybe I have included it in the wrong way. I hope someone can help me. Here are my methods:
Alarm method from Activity.class
(UhrzeitInMillis describes the chosen time by timepicker, for example 16.03):
public void SetAlarm(Context context, long UhrzeitInMillis) {
Intent intent = new Intent(context, Optionen_Alarm.class);
final int id = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), id, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, UhrzeitInMillis, AlarmManager.INTERVAL_DAY, pendingIntent);
}
BroadcastReceiver (Optionen_Alarm.java):
public class Optionen_Alarm extends BroadcastReceiver {
#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, "myapp:mywakelocktag");
wl.acquire();
createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1");
builder.setContentTitle("titel");
builder.setContentText("text!");
builder.setSmallIcon(R.drawable.picture);
builder.setColor(context.getResources().getColor(R.color.red));
builder.setVibrate(new long[]{0, 300, 300, 300});
builder.setLights(Color.WHITE, 1000, 5000);
builder.setAutoCancel(true);
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("text!"));
Intent notifyIntent = new Intent(context, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notificationCompat = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(15, notificationCompat);
wl.release();
private void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "name";
String description = "description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel("1", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
```java
For battery reason, from android 6.0 the time you set on the alarm manager will not be guaranteed to trigger at the exact same time you have set. You could use the method '''setExactAndAllowWhileIdle()''' to make the alarm behave like you want.
You can read more about this here https://developer.android.com/training/scheduling/alarms

Update Notification with a Button click

I just a newbie of Android, while I programming I had the problem that is about the Notification.
I need your help to process updating notification.
The context of this like when you are playing the game and you had a notification about another game (the second game is running in the background). Then you have a new notification of the second game which has the same ID of the previous notification.
This is my declaration:
I used NotificationManagerclass to create a Notification.
private NotificationManager manager;
private int notiId = 6789; // Each notification will be managed by an ID
private int numMsg = 0;
This is the function clickToSend button:
public void clickToSend(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Setting Notification Properties
builder.setContentTitle("New Message");
builder.setContentText("Notification Demo: Message has received");
builder.setTicker("Message Alert");
builder.setSmallIcon(R.drawable.ic_action_unread);
builder.setNumber(++numMsg);
Intent intent = new Intent(this, NotificationDetailActivity.class);
TaskStackBuilder stack = TaskStackBuilder.create(this);
stack.addNextIntent(intent);
PendingIntent pendingIntent = stack.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notiId, builder.build());
}
I think code of function clickToUpdate that will process like the clickToSend function.
Thanks for your help!
My language is not good. I'm sorry for the inconvenience.

Push Notifications - Android

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());
}

android notification banner not displaying

for some reason when I make a notification appear on my app in will vibrate and make noise but no banner appears across the top of the phone. Is there a specific command I need to make it do this?
public Notification getNotification(String message) {
Intent intent = new Intent(serviceContext, NotificationGenerator.class); //not sure how
// this class i pass matters
PendingIntent pi = PendingIntent.getActivity(serviceContext, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(serviceContext)
.setContentTitle(message)
.setContentText(message)
.setSmallIcon(R.drawable.dominos_icon)
.setContentIntent(pi);
Notification n = builder.build();
n.defaults = Notification.DEFAULT_ALL;
return n;
}
Your code will work fine once you will add the lines below:
NotificationManager n_mngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
n_mngr.notify(NOTIF_ID, n);

I Have a notification in the status bar code, but AIDE is marking two things as wrong

I need to make a Status Bar Notification and I got this code from research, but it doesn't seem to be working out when I placed the code into MainActivity.java with AIDE
NotificationManager
mNotificationManager = (NotificationManager)
getSytemService(Context.N);
Notification notification = new notification(R.drawble.ic_launcher,
"Notification Test", System.currentT;
Context context = getApplicationContext();
CharSequence contentTitle = "My notification Title";
CharSequence contentText ="This is the message";
Intent notificationIntent = new Intent(this, MainActivity.class);
The errors seem to be at Line 3 with the (Context.N) where the N has the error message: Unknown member 'N' of 'android.content.Context'. The other error message is on the fifth line where it reads System.currentT with the error message of Unknown member 'currentT' of 'java.lang.Sytem'.
Context.N should be Context.NOTIFICATION_SERVICE.
System.currentT should be System.currentTimeMillis().
It seems that you are copying the code from somewhere but got the code truncated?
Here's a sample method for generating notifications.
This is based on Android's doc: Building a Notification. For more details (e.g. how to display a progress bar or an extended view), please read the docs.
private static void generateNotification(Context context, String messageTitle, String messageText)
{
// Get notification manager.
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Setup notification builder.
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(messageTitle)
.setContentText(messageText)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL);
// Create intent.
final Intent resultIntent = new Intent(context, MainActivity.class);
// Setup task stack builder.
final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addParentStack(MainActivity.class);
taskStackBuilder.addNextIntent(resultIntent);
// Create pending intent.
final PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Update notification builder.
notificationBuilder.setContentIntent(resultPendingIntent);
// Post notification.
notificationManager.notify(0, notificationBuilder.build());
}
The NotificationCompat.Builder class requires Android's version 4 Support Library.

Categories