Notification within 24 hours - java

I created a method to send a notification to the user named sendNotification () using NotificationCompat.Builder and NotificationManager.
I need this notification to be posted at a fixed interval of 24 hours or even at a specific time, for example every day at 07:00 AM, which in this case would result in the same 24 hours, which may be adjusted by the user in the future.
It seems to me that with the public class AlarmManager it is possible to perform this procedure, but I am not sure if I have to create a service or if it would be the service itself.
How could this notification be done within this 24-hour ?

public void setLocalNotification(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(this, LocalNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 99, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Log.d("TAG ","LocalNotification Start");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pendingIntent);
}
public class LocalNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TUS-NOTAS ", "LocalNotification Receiver");
Intent service1 = new Intent(context, ShowNotificationService.class);
context.startService(service1);
}
}
public class ShowNotificationService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private final static String TAG = "ShowNotification";
public ShowNotificationService()
{
super("ServiceNotification");
}
public ShowNotificationService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
Context context = this.getApplicationContext();
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, SplashActivity.class);
pendingIntent = PendingIntent.getActivity(context,99, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getResources().getString(R.string.app_name));
builder.setVibrate(new long[] { 200, 200});
builder.setSound(uri);
if (Global.getStringKey(getApplicationContext(), Definitions.LANGUAGE_VALUE).equals("en"))
{
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("We miss you!"));
builder.setContentText("You have not added any notes recently.");
}else if (Global.getStringKey(getApplicationContext(),Definitions.LANGUAGE_VALUE).equals("es"))
{
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("Te extrañamos!"));
builder.setContentText("No has agregado notas recientemente.");
}
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo_app);
builder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Log.d("TUS-NOTAS"," LocalNotification Service");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
}
}

0 0 7 1/1 * ? *
This is a cron statement made from http://www.cronmaker.com/. You can use this in a cron job that executes everyday at 7 am.

Related

Scheduling Notification in Android Studio not working, Alarmanager not working

I tried to schedule a notification, but when i run the app it doesn't show up after the 3s delay i set.
I followed this tutorial but it didn't work https://betterprogramming.pub/scheduled-notifications-in-android-2055356fb4f5.
public class NotificationsService {
private final Activity activity;
final int requestCode = 1;
#RequiresApi(api = Build.VERSION_CODES.S)
public NotificationsService(Activity activity)
{
this.activity = activity;
scheduleAlarm();
}
#RequiresApi(api = Build.VERSION_CODES.S)
public void scheduleAlarm()
{
Intent intent = new Intent(activity,AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(
activity,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
AlarmManager manager = (AlarmManager) activity.getSystemService(ALARM_SERVICE);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+3000,pi);
Log.d("xxx","scheduled alarm");
}
public static class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Log.d("xxx","creating notification");
String CHANNEL_ID = "Channel1";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.fish)
.setContentTitle("Dont forget to clean your fish tank.")
.setContentText("One week as passed, it is time for you to replace at least 25% of the water in the aquarium.")
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "My Fishy";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
notificationManager.notify(1,notificationBuilder.build());
}
}
}
}
`
I expect the notification to show up after 3s.

Not able to receive data in activity from foreground service in app android

I am making an app that reads data being sent via Bluetooth in one activity which then is redirected to a foreground service which sends an intent to another activity where the data will be processed. I know I am missing something in the code for the broadcast receiver on the activity code.
If anyone can give me advice or help me with the data being able to be processed. There are no crashes so far. I am new in coding in android studio and any help would be great!
*** This is the code for the Foreground Service ***
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate(){
super.onCreate();
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//super.onStartCommand(intent, flags, startId);
String input = intent.getStringExtra("inputExtra");
Log.i("Tag", input);
sendData(input);
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
private void sendData(String input){
Log.i("Tag", "inside sendData");
Intent intent = new Intent();
intent.setAction("com.example.Pillwoah.sendbroadcast");
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("inputExtra", input);
sendBroadcast(intent);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
*** This is the code for the activity ***
public class MainActivity5 extends AppCompatActivity {
protected static final String TAG = "TAG";
TextView dataText;
BroadcastReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
Log.i(TAG, "data sending");
configureReceiver();
}
class DataBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String message = "Broadcast intent detected " + intent.getAction();
Log.i(TAG, message);
}
}
private void configureReceiver(){
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.Pillwoah.sendbroadcast");
receiver = new DataBroadcastReceiver();
registerReceiver(receiver, filter);
}
}

Using ArrayList from Activity in BroadcastReceiver

I have an arrayList in the MainActivity, and I'm using alarmManager to show notifications when the app is closed. I don't know how I can use that arraylist in the BroadcastReceiver "inside onReceive() method" and get data from that arraylist to show it in the Notifications. I also want to be able to remove the element from the arraylist that has already been shown in the notification.
anyway this my code, I hope you can help me !
-MainActivity :
NotificationManager mNotificationManager;
int NOTIFICATION_ID = 0;
private static final String ACTION_NOTIFY = "com.example.android.standup.ACTION_NOTIFY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent notifyIntent = new Intent(ACTION_NOTIFY);
final PendingIntent notifyPendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
ToggleButton toggleButton = findViewById(R.id.alarmToggle);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
long triggerTime = SystemClock.elapsedRealtime()+10000;
long repeatInterval = 180000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, repeatInterval, notifyPendingIntent);
}else {
mNotificationManager.cancelAll();
alarmManager.cancel(notifyPendingIntent);
}
}
});
}
AlarmReceiver Class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent contentIntent = new Intent(context, MainActivity.class);
PendingIntent contentPendingIntent = PendingIntent.getActivity
(context, createID(), contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Hello")
.setContentText("Notification Text")
.setContentIntent(contentPendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
notificationManager.notify(createID(), builder.build());
}
public int createID(){
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
return id;
}
}
Thank you !

Notification action button dosen't stop the alarm ringtone

I set an alarm and i want to disable the ongoing alarm using notification action button without opening the activity.
I have attached my whole code below.
When user set alarm it call the broadcast receiver and from them i call my ringtone service to start ringtone. and it will fire a notification. in that notification it will have a disable button. i have done all the resource i had found on internet. but
disable button on notification didn't work. where is my fault
onToggled button to start alarm from main activity
public void OnToggleClicked(View view) {
long time;
if (((ToggleButton) view).isChecked()) {
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
} else {
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
}
intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// setRepeating() lets you specify a precise custom interval--in this case,
// 1 minutes.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
My broadcast receiver class
public class AlarmReceiver extends BroadcastReceiver {
public static Ringtone ringtone;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
// using service class
Intent i = new Intent(context, RingtonePlayingService.class);
context.startService(i);
createNotification(context);
}
public void createNotification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("It is prayer time")
.setContentText("Prayer")
.setSmallIcon(R.mipmap.ic_launcher)
.setSubText("Tab to cancel the ringtone")
.setPriority(NotificationCompat.PRIORITY_HIGH);
//To add a dismiss button
Intent dismissIntent = new Intent(context, RingtonePlayingService.class);
dismissIntent.setAction(RingtonePlayingService.ACTION_DISMISS);
PendingIntent pendingIntent = PendingIntent.getService(context,
123, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action = new NotificationCompat.Action
(android.R.drawable.ic_lock_idle_alarm, "DISMISS", pendingIntent);
builder.addAction(action);
// end of setting action button to notification
Intent intent1 = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 123, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(123, notification);
}
My ringtoneplaying service class
public class RingtonePlayingService extends Service{
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
private Ringtone ringtone;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand");
if(intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
String action = intent.getAction();
if(ACTION_DISMISS.equals(action))
dismissRingtone();
return START_NOT_STICKY;
}
public void dismissRingtone() {
Intent i = new Intent(this, RingtonePlayingService.class);
stopService(i);
}
#Override
public void onDestroy() {
ringtone.stop();
}
That was my fault
When i click on disable on notification it again call the receiver class that's why ringtone keeps playing. So i keep some modifying and it works fine.
public class RingtonePlayingService extends Service {
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
private Ringtone ringtone;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if (intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
String action = intent.getAction();
if (ACTION_DISMISS.equals(action))
dismissRingtone();
else {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
}
return START_NOT_STICKY;
}
public void dismissRingtone() {
// stop the alarm rigntone
Intent i = new Intent(this, RingtonePlayingService.class);
stopService(i);
// also dismiss the alarm to ring again or trigger again
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
aManager.cancel(pendingIntent);
// Canceling the current notification
NotificationManager notificationManager =
(NotificationManager)getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.cancel(321);
}
#Override
public void onDestroy() {
ringtone.stop();
}}

Notification everyday at specific time not notifying

I want to generate notification everyday at 8:00 AM. I have created the code for simple notification but I am not getting the notification following is the code for NotifyService Class
public class NotifyService extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*Notification Related*/
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Thought")
.setContentText("Get Today's Thought");
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
//mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
And this is the code written in the MainActivity class onCreate method
PendingIntent pendingIntent;
Intent myIntent = new Intent(this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY,8);
calendar1.set(Calendar.MINUTE,00);
calendar1.set(Calendar.SECOND,00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);
Don't know where I am getting wrong
I don't think you have created a service here. Notifyservice class extends AppCompatActivity. You should extend Service class to make it a service.
Best solution for your problem can be found with the following steps
Create a service for alarmnotification
Create a receiver to start the service of alarmnotification
add the receiver and service into manifest.xml too
Follow the steps of given url.
http://karanbalkar.com/2013/07/tutorial-41-using-alarmmanager-and-broadcastreceiver-in-android/
MainActivity
public class MainActivity extends AppCompatActivity {
AlarmManager alarmManager;
PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Button setAlarm= (Button)findViewById(R.id.button);
setAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 00);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 10, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
});
}
}
AlarmReceiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Intent startIntent = new Intent(context, NotificationService.class);
context.startService(startIntent);
Log.e("TRIGGER", "ALARM TRIGGERED");
}
}
NotificationService
public class NotificationService extends Service {
#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 void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Intent inn=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
inn, 0);
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test Message")
.setContentText("Hi, you have one notification");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Add this in your AndroidManifest file
<receiver android:name=".AlarmReceiver"></receiver>
<service android:name=".NotificationService"/>

Categories

Resources