android alarm manager repeat every two years - android

In my android application i need to show notification to user every two years at 09.00. I used the following method but did not work exactly
AlarmManager.INTERVAL_DAY * 30 * 6 * 4
and the following code is my full alarm manager
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
private AlarmManager AlarmManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(2018,2,9,9,0);
AlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY * 30 * 6 * 4, pendingIntent);
}
}

Related

Receiver is not being called by AlarmManager - Android

I have written this class to call reciver every 24 hours
I was trying to use same receiver for "SabahReceiver" then i added another receiver "MasaReceiver", all possibilities did not work for me!
anybody can tell me whats going wrong !?
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.mbh.test.receivers.MasaReciever;
import com.mbh.test.receivers.SabahReciever;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by MBH on 17/12/15.
*/
public class SabahMasaAlarmManager {
public static final int MINUTE = 60000;
public static final int HOUR = 1000 * 60 * 60;
public static final int DAY = 86400000;
private PendingIntent mSabahPendingIntent;
private PendingIntent mMasaPendingIntent;
private Context mContext;
private void SetupAlarms() {
/* Retrieve a PendingIntent that will perform a broadcast */
Intent sabahAlarm = new Intent(mContext, SabahReciever.class);
// sabahAlarm.putExtra(SabahReciever.KEY_IS_SABAH, true);
mSabahPendingIntent = PendingIntent.getBroadcast(mContext, 100, sabahAlarm, 0);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent masaAlarm = new Intent(mContext, MasaReciever.class);
// sabahAlarm.putExtra(SabahReciever.KEY_IS_SABAH, false);
mMasaPendingIntent = PendingIntent.getBroadcast(mContext, 101, masaAlarm, 0);
}
public void StartAlarm() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss" );
Date now = Calendar.getInstance().getTime();
Calendar sabahDate = Calendar.getInstance();
sabahDate.set(Calendar.HOUR_OF_DAY, 23);
sabahDate.set(Calendar.MINUTE, 47);
sabahDate.set(Calendar.SECOND, 0);
// sabahDate.set(Calendar.HOUR_OF_DAY, 6);
// sabahDate.set(Calendar.MINUTE, 0);
if(sabahDate.getTime().before(now)){
sabahDate.add(Calendar.DAY_OF_YEAR, 1);
}
Log.d("DATE", "Sabah: "+ dateFormat.format(sabahDate.getTime()));
Calendar masaDate = Calendar.getInstance();
masaDate.set(Calendar.HOUR_OF_DAY, 23);
masaDate.set(Calendar.MINUTE, 49);
// masaDate.set(Calendar.HOUR_OF_DAY, 20);
// masaDate.set(Calendar.MINUTE, 0);
masaDate.set(Calendar.SECOND, 0);
if(masaDate.getTime().before(now)){
masaDate.add(Calendar.DAY_OF_YEAR, 1);
}
Log.d("DATE", "Masa: "+ dateFormat.format(masaDate.getTime()));
AlarmManager manager = (AlarmManager) mContext.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, sabahDate.getTimeInMillis(), DAY, mSabahPendingIntent);
// manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, 86400000, mSabahPendingIntent);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, masaDate.getTimeInMillis(), DAY, mMasaPendingIntent);
// manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+20000, 86400000, mMasaPendingIntent);
}
public void cancelAlarm() {
AlarmManager managerSabah = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
managerSabah.cancel(mSabahPendingIntent);
AlarmManager managerMasa = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
managerMasa.cancel(mMasaPendingIntent);
}
public SabahMasaAlarmManager(Context baseContext) {
mContext = baseContext;
SetupAlarms();
}
}
setInexactRepeating() is not bound to fire the alarm exactly after the mentioned time. There may be some delay or it may fire a bit early. Basically framework 'batch' the inexact alarms to fire all at one time. Use setExact. Also consider the deep sleep mode. See How to use CPU to perform any operation in deep sleep mode. As you want alarm to fire once in 24 hours, there are good chances that device will be in sleep mode when alarm fires.

android no notification popup in statusbar

there're two problems here. I try to let user select a specific time to make app reminder users to use app. Once user set up a time say 8:00 pm. The notification should pop up every day. However, After I used
"NotificationManager" and "Notification"
first of all, there's nothing pop-up. For example, now is 1:19 am in AU, then, i set-up this app to 1:20 am to display the notification in the status bar as a test.
Secondly, if in my TabBar class i use
nm.cancel(getIntent().getExtras().getInt("NotifID"));
It will get a null pointer exception
Here is my code:
TabBar.class
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancel(getIntent().getExtras().getInt("NotifID"));
Notification.class
package com.example.tabpro;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
public class SettingNotification extends Activity{
TimePicker timePicker;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_notification);
Button btnset = (Button) findViewById(R.id.btnSetAlarm);
btnset.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
timePicker = (TimePicker) findViewById(R.id.timePicker_settime);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calendar.set(Calendar.SECOND, 0);
Intent i = new Intent("com.example.tabpro.DisplayNotification");
Intent i2 = new Intent(SettingNotification.this, TabBar.class);
i.putExtra("NotifID", 1);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0, i, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), displayIntent);
startActivity(i2);
}
});
}
}
DisplayNotification.class
package com.example.tabpro;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class DisplayNotification extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
int notifID = getIntent().getExtras().getInt("NotifID");
Intent i = new Intent("com.example.tabpro.TabBar");
i.putExtra("NotifID", notifID);
PendingIntent detailsIntent = PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.ic_launcher, "Time's up!", System.currentTimeMillis());
CharSequence from = "AlarmManager - Time's up!";
CharSequence message = "This is your alert, courtesy of the AlarmManager";
notif.setLatestEventInfo(this, from, message, detailsIntent);
finish();
}
}
You need to call notify() on your NotificationManager to actually show the Notification. Since you never call this method, your Notification is never shown.
Your NullPointerException is likely a different problem. For that, you should do some debugging yourself. First, you need to determine what is null. Then determine why it is null and fix it. In your code, the most likely candidates for causing the NPE in TabBar are nm, getIntent(), and getExtras().
Hope this helps :
You need to call notify() method to display notification in your notification tray of your device.
Below is the code for that:
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context, YourActivity.class), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(yourappname).setWhen(0)
.setAutoCancel(true).setContentTitle(yourappname)
.setContentText(yourmessage).build();
notificationManager.notify(0, notification);

How to start an activity using AlarmManager etc

I am trying to start code inside an activity at regular intervals using Alarm manager. I have looked at various examples on here but they have not really helped.
For testing purposes, all I am trying to do is pop up a toast at 10 second intervals, but nothing seems to be happening at all. Please help guys!
I have this in the manifest (also declarations for all three activities):
<receiver android:name=".receiver.AlarmReceiver"></receiver>
Code from main activity, in OnCreate:
//
// Setting up the Alarm Manager
//
Intent myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long timerInterval = 10 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timerInterval, pendingIntent);
//finish();
AlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context," onRecieve() test" , Toast.LENGTH_LONG).show();
Intent scheduledIntent = new Intent(context, MyService.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
MyService.java:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Toast.makeText(getBaseContext(),"test message.",
Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Your activity is not showing, because you are calling startActivity() on an Intent that identifies a Service. You should see warnings related to this in LogCat.
I humbly suggest that you use LogCat yourself, via the Log class, for logging background operations, rather than attempting to use a Toast.
test this code:
private void establecerAlarmaClick(int when){
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivityAlarmita.this, MainActivityAlarmita.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityAlarmita.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when * 1000, pendingIntent);
}

Using a broadcast receiver to start AlarmManager in Android?

I am writing a program that fires off an intent to start a service periodically, to do this I have decided to use alarmmanager, I was able to make this do what I wanted in an activity fairly easily but I'm getting an error when attempting to do it in a receiver that I'm unable to figure out.
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
tells me that ALARM_SERVICE can't be resolved to a variable
here is my complete code for that receiver:
package com.testapp21.second.activities;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class PhoneOnReceiver extends BroadcastReceiver {
private PendingIntent mAlarmSender;
#Override
public void onReceive(Context context, Intent intent) {
mAlarmSender = PendingIntent.getService(context,
0, new Intent(context, StatsCheckerService.class), 0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 30*1000, mAlarmSender);
}
}
Try
AlarmManager am = (AlarmManager)context.getSystemService(Service.ALARM_SERVICE);
I found that if you are in a fragment you can do this
AlarmManager am = (AlarmManager)getActivity().getSystemService(Service.ALARM_SERVICE);

Android : how to set the calendar alert in android

Is it possible to show calendar alert in android, so that on the specified date the alert should pop up and remind the user regarding the task.
Sorry, there isn't currently a calendar API in the SDK. You can however implement your own alarm with the AlarmManager showing your own UI at the time you schedule with it.
first of all to set the alert in calendar application you have to make the permit-ion :
Now, that the alarm receiver is set, lets take a look at the class that will set and cancel the alarms:
package SomeApp.SomeApp;
import java.util.Calendar;
import java.lang.String;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.util.Log;
import android.content.Intent;
import android.widget.Toast;
/**
* When this code is run only one alert will be displayed even though 2 alerts were
* were setup (as one of them will be cancelled later on
*/
public class SomeApp extends ListActivity {
/* for logging - see my tutorial on debuggin Android apps for more detail */
private static final String TAG = "SomeApp ";
protected Toast mToast;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert_list);
try {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+30000, sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+15000, sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}
}
You will notice that this is only a "one-shot" alarm. If you want to set a repeating alarm, it is explained in Android's documentation. However, I will write on that too if there is demand for it. Now, let's examine the code. For setting an alarm, you will need 4 things:
The class that's setting the alarm
The class that will be called when the alarm "goes off"
The time at which the alarm should go off
A requestCode (which will use as a unique ID to identify the alarms) used in PendingIntent.
For cancelling an alarm, you need 3 things:
The class that set the alarm
The class that was to be called when the alarm "goes off"
The requestCode you used for PendingIntent object.
We have covered 2 things - the declaration of the receiver in our manifest file and the class that sets and cancels alarms. Now, we need to look at the class that will be called when the alarm goes off.
package someApp.someApp;
import java.util.Calendar;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.util.Log;
import android.widget.Toast;
/** All receiver classes must extend BroadcastReceiver */
public class AReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context con, Intent in) {
try {
/* Display an alert */
Toast.makeText(con, "hello my jello ", Toast.LENGTH_LONG).show();
} catch (Exception r) {
Toast.makeText(con, "You were supposed to do something"
+" now but I can't retrieve what it was.",
Toast.LENGTH_SHORT).show();
Log.e("ALARM_RECEIVER", r.toString());
}
}
}
AND YOU are able to use this other ans also...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 0);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
setAlarm(cal);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 30);
setAlarm(cal);
//etc
}
public void setAlarm(Calendar cal) {
try {
Intent intent = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}

Categories

Resources