I am trying to add a notification feature to my application. I want it to run a notification or action at the same time, every day. I have this code for my notification right now:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 45612;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
// Build the notification
notification.setSmallIcon(R.drawable.icon);
notification.setTicker("Brook Betterment Plan");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Brook Betterment Plan");
notification.setContentText("Don't forget to enter your daily stats! ");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
// Builds notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
}
Thanks! Hope someone knows the answer. Also, I was hoping it wouldn't need any additional Activitys or Java class's.
Alarm Manager
public static void startAlarmBroadcastReceiver(Context context) {
Intent _intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Alarm Broadcast Receiver
In AndroidManifest, just define the class as
<receiver android:name=".AlarmBroadcastReceiver" >
</receiver>
And code will be like
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
void showNotification(Context context) {
String CHANNEL_ID = "your_name";// The id of the channel.
CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
NotificationCompat.Builder mBuilder;
Intent notificationIntent = new Intent(context, TestActivity.class);
Bundle bundle = new Bundle();
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setContentTitle("Title");
} else {
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(Notification.PRIORITY_HIGH)
.setContentTitle("Title");
}
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("Your Text");
mBuilder.setAutoCancel(true);
mNotificationManager.notify(1, mBuilder.build());
}
}
Create a class that will generate notification, like LocalNotification
Add the code you have in on create in that class under a method like showDailyNotification
Now use JobScheduler and schedule a job for every 24 hours, when the job is started call this method in LocalNotification
Make LocalNotification a singleton class.
BTW don't forget to use notification channel because otherwise it will not work on Oreo and above devices.
Related
I have RecyclerView that contains notes, when I add new note I want to add reminder for that particular note but when the notification appears and I click on it I want to navigate to that activity and open that note. Notification works properly but what I want is, when I clicked on the notification open that note I set reminder on it.
AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, ChecklistChildActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "alarmChannel")
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.drawable.alarm)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(123, builder.build());
}
}
setAlarm method:
private void setAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
I have an o'clock interface in RecyclerAdapter that I implemented in MainActivity:
#Override
public void onNoteClicked(int position, View itemView) {
Intent intent = new Intent(this, NoteDetail.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("id", noteAdapter.itemList.get(position).getId());
intent.putExtra("title", noteAdapter.itemList.get(position).getTitle());
intent.putExtra("content", noteAdapter.itemList.get(position).getContent());
intent.putExtra("date", noteAdapter.itemList.get(position).getDate());
intent.putExtra("backgroundColor", noteAdapter.itemList.get(position).getBackgroundColor());
startActivity(intent);
}
When I clicked on the notification this method somehow should be called. When I add the note I don't know which position it goes in order to pass that position with the intent, though if I know the position, the position may change when I add or remove another note.
Great, I have an idea, I assume your activity gets id and other data from intent. so we have to put data to alarm intent and read them from AlarmReceiver and put them again into the Activity Intent.
private void setAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("id", "myId");
intent.putExtra("title", "my title");
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
and get that from the Receiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, ChecklistChildActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("id", intent.getStringExtra("id"));
i.putExtra("title", intent.getStringExtra("title"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "alarmChannel")
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.drawable.alarm)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(123, builder.build());
}
that is a simple way but I suggest using the database in your activity and getting the note details in the onCreate method with id, so you need just add id in your intents and add get query in NoteDetail.java class.
I am able to get notifications at a particular time in future by using Calendar class java (Example 9:15am). The Alarm manager sends the broadcast to the broadcast receiver whenever the time is 9:15am but when I open the app after 9:15am (Example 9:20am). I receive the same notification. Can anyone help my about this.
My Manifest
<receiver android:name=".others.NotificationReceiver"/>
Notification Receiver.java
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context);
}
private void createNotification(Context context) {
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel linkChannel = new NotificationChannel(link_channel_id, "Link Channel", NotificationManager.IMPORTANCE_HIGH);
linkChannel.setDescription("This channel is used to show Zoom Links");
notificationManager.createNotificationChannel(linkChannel);
}
Notification notification = new NotificationCompat.Builder(context, link_channel_id)
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setContentTitle("Test Notification")
.setContentText("This is a test notification")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
My Alarm Manager
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 10);
calendar.set(Calendar.SECOND, 0);
Intent myIntent1 = new Intent(this, NotificationReceiver.class);
myIntent1.setAction(ACTION_ONE);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 1, myIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
I want to set a notification to be shown in a specific time, like 10AM. I already searched this the web and did this, but I don't know what is wrong cause nothing is notifying! Here are my notification class:
public class notification extends AppCompatActivity {
NotificationManager manager;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(notification.this,about.class);
PendingIntent pendingIntent = PendingIntent.getActivity(notification.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(notification.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.up);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setNumber(100);
myNotication = builder.getNotification();
manager.notify(0, myNotication);
}
And my main class(activity)(onCreate method):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(main.this,notification.class);
intent.putExtra("uur", "1e");
pendingIntent = PendingIntent.getBroadcast(main.this, 0, intent, 0);
timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, 01);
timeOff9.set(Calendar.MINUTE, 46);
timeOff9.set(Calendar.SECOND, 0);
alarmMgr0.set(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), pendingIntent);
i think you should modify this below code as your requirement
private void handleNotification() {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, pendingIntent);
}
and This is custom BroadcastReceiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Calendar now = GregorianCalendar.getInstance();
int dayOfWeek = now.get(Calendar.DATE);
if(dayOfWeek != 1 && dayOfWeek != 7) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(context.getResources().getString(R.string.message_box_title))
.setContentText(context.getResources().getString(R.string.message_timesheet_not_up_to_date));
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
}
And add manifest application tag:
<receiver
android:name="be.menis.timesheet.service.AlarmReceiver"
android:process=":remote" />
modify this code as your need i think this is useful
I am developing an Android prayer app for Muslims. I have already developed the code to obtain the prayer times with the help of praytimes.org. Now I want to make it so that the user is notified at that time to pray. But for now, I just want to be able to send a notification at a certain time. Looking at the code and online resources, it seems to me as if it should work but for some reason, the notification is not displaying. I know the code for the notification part is correct because I created a button to create a notification using that code and it works. So I believe the problem is with the service, receiver, or alarmManager.
My guess is the problem has to do with the onStartCommand() method in MyNotificationService.java. I am not too familiar with services and their life-cycles so please go easy on me.
Thanks in advance.
In my MainActivity.java, here is the code in my onCreate() method.
/*========================Begin Notification Code==============================*/
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 18);
calendar.set(Calendar.HOUR_OF_DAY, 4);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent intent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
/*========================End Notification Code==============================*/
Here is MyReceiver.class
package com.ahmed.omar.tawheed;
/**
* Created by Omar on 1/18/15.
*/
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service = new Intent(context, MyNotificationService.class);
context.startService(service);
}
}
Here is MyNotificationService.java
package com.ahmed.omar.tawheed;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class MyNotificationService extends Service {
private NotificationManager notificationManager;
private int prayerNotificationID = 420; //blazeIt
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public int onStartCommand(Intent intent1, int flag, int startId) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification n = new NotificationCompat.Builder(this)
.setContentTitle("Time to Pray")
.setContentText("It is now time to pray salah")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
n.flags = Notification.FLAG_AUTO_CANCEL;
// Sending the notification itself
notificationManager.notify(prayerNotificationID, n);
return START_STICKY;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Here are the lines from my AndroidManifest.xml
<service android:name=".MyNotificationService"
android:enabled="true" />
<receiver android:name=".MyReceiver"/>
See the documentation for Calendar.MONTH. The valid values start at 0 (for January), not 1. So, your code is trying to set an alarm on February 18, not January 18. Try changing the Calendar.MONTH value to 0 instead of 1.
This is what i do for send notification.
fun showNotification(context: Context,title: String, message: String) {
Log.e("notification", "visible")
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = NotificationChannel("1",
"NAMAJ_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT)
channel.description = "namaj alarm channel"
mNotificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(context, "1")
.setSmallIcon(com.waltonbd.muslimcalender.R.mipmap.ic_launcher) // notification icon
.setContentTitle(title) // title for notification
.setContentText(message)// message for notification
.setAutoCancel(true) // clear notification after click
val intent = Intent(context, MainActivity::class.java)
val pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
mBuilder.setContentIntent(pi)
mNotificationManager.notify(0, mBuilder.build())
}
I am getting "The method getSystemService(String) is undefined for the type AlarmManagerBroadcastReceiver" error. I even tried to put getActivity() before it but it was of no help.
code for AlarmManagerBroadcastReceiver.java
package com.archana.pocketfriendly;
import java.text.Format;
import java.text.SimpleDateFormat;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
MediaPlayer alarm;
#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();
//You can do the processing here update the widget/remote views.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
alarm = MediaPlayer.create(context, R.raw.alarm);
alarm.start();
msgStr.append("Do you want to enter the expenses?\nIgnore if already done!");
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
Vibrator vib=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(2000);
// notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.settings)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainMenu.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainMenu.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //error in this `enter code here`line.
mNotificationManager.notify(0, mBuilder.build());
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 86400 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Please let me know if any other information is required.
Just like your other calls to getSystemService, you need to perform it on a context object:
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);