Send notification at a certain time - java

I have this code that send a notification. I copied from one of the forums here ! So this code says that sends a notification in a certain time , but i'm not being able to send it , any problems with my code ?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 51);
calendar.set(Calendar.SECOND, 20);
Intent intent1 = new Intent(Testes.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Testes.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) Testes.this.getSystemService(Testes.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
AlarmReceiver.class:
public class AlarmReceiver extends BroadcastReceiver {
public static int MID = 0;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, Testes.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.grades_icon)
.setContentTitle("Alarm Fired")
.setContentText("Events To be PErformed").setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(MID, mNotifyBuilder.build());
MID++;
}
}

Here is my Alarm Code that works just fine.
public class 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.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "");
wl.acquire();
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
sendNotification("Alarm",context);
intent = new Intent();
intent.setClass(context, AlarmActivity.class); //AlarmActivity is a dummy class name where to redirect
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("msg","Task Pending");
context.startActivity(intent);
wl.release();
}
sendNotification(String s,Context c) is given below.
private void sendNotification(String body,Context context) {
Intent intent = new Intent(context, WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT);
//Set sound of notification
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.mipmap.ic_launcher_round);
NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(true)
.setContentText("lalalalalala lalalalalal lalalalalalal lalalalaaa")
.setSound(notificationSound)
.setContentIntent(pendingIntent);
Notification not = notifiBuilder
.setContentTitle("The Big Notification")
.setContentText(body)
.setStyle(new NotificationCompat.BigPictureStyle(notifiBuilder)
.bigLargeIcon(icon))
.build();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(123456 /*ID of notification*/, notifiBuilder.build());
}
and then in my AlarmActivity the code is as follow.
public class AlarmActivity extends AppCompatActivity {
private Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
setContentView(R.layout.activity_alarm);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
r = RingtoneManager.getRingtone(this, notification);
r.play();
ImageView buttonCancelAlarm = (ImageView) findViewById(R.id.buttonCancelAlarm);
buttonCancelAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancelAlarm(Test.this);
finish();
}
});
}
public void cancelAlarm(Context context)
{
r.stop();
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 12345, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
and you can add your alarm through this function
public void setAlarm(Context context, long millisec)
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 51);
calendar.set(Calendar.SECOND, 20);
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 12345, i, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(context,"Alarm Saved!",Toast.LENGTH_SHORT).show();
}
I hope it helps. Now you can add your calendar intent in it and it will work.

Related

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 !

Show notification on particular date and time using task scheduler

I am new on android. I want to show notification on a particular date and time(For e.g on date 9 September 2017 on time 10:00 AM) in my app. I am using alarm manager but it does not work properly.
Please tell me the proper way.
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2017);
calendar.set(Calendar.MONTH, 9);
calendar.set(Calendar.DAY_OF_MONTH, 9);
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent inn = new Intent(MainActivity.this,AlarmActivity.class);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0,inn, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), displayIntent);
}
AlarmActivity
public class AlarmActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content_alarm);
final Intent notificationIntent = new Intent(this, AlarmActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(AlarmActivity.this, 0, notificationIntent, 0);
Notification notification1 = new Notification.Builder(AlarmActivity.this)
.setContentTitle("Notification")
.setContentText("Get Notigication")
.setContentIntent(contentIntent).setWhen(System.currentTimeMillis())
.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification1);
}
Manifest
Permission
In order to trigger alarm you have to use WakefulBroadcastReceiver from where you will trigger a service that will generate notification in you activity.
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Then you will create a service like this.
public class AlarmService extends IntentService {
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
contentId = intent.getStringExtra("id");
String title = intent.getStringExtra("title");
String subtitle = intent.getStringExtra("subtitle");
sendNotification(title, subtitle);
}
public void sendNotification(String title, String subtitle) {
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.reminder_notification_view);
contentView.setInt(R.id.layout, "setBackgroundColor",
Color.WHITE);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, subtitle);
notification.contentView = contentView;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notification.contentIntent = PendingIntent.getActivity(this, someRandomId,
intent, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND; // Sound
mNotificationManager.notify(someRandomId, notification);
}
}

Issue in setrepeating() in android alarmmanger?

I have tried alarmanager in order to get daily notification in android.... The alarm do start at specified time but gets repeated every minute after that...I have specified INTERVAL_DAY in setrepeating() function of Mainactivity but it does not seems to work. It contains three parts Mainactivity, MyReceiver & AlarmService. Can anyone seems to fix this ??
Mainactivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
// we can set time by open date and time picker dialo
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 10);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(MainActivity.this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(this.ALARM_SERVICE);
Log.e("Tag","calling here");
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),864000, pendingIntent);
}
}
MyReceiver
public class MyReceiver extends BroadcastReceiver{
int MID=0;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.icon)
.setContentTitle("Alaram Fired")
.setContentText("Events To be PErformed").setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(MID, mNotifyBuilder.build());
MID++;
}
}
MyAlarmService
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
Log.e("Tag1","alarmservice here");
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.icon,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_CANCEL_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//notification.setLatestEventInfo(this.getApplicationContext(), "Daily Notification Demo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
AlarmManager.setRepeating doesn't work properly on different android versions.
Try setExact. It won't repeat but you can achieve repeating functionality as mentioned below:
Update MyReceiver
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExact(AlarmManager.RTC_WAKEUP, (864000 + System.currentTimeMillis()),pendingIntent);
Here we schedule alarm again by calculating nextAlarmTime using 864000 + System.currentTimeMillis();

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