so im trying to set a scheduled alarm in my android app. so the setting alarm service is here below. please tell me if its correct or not since it isnt working.
Context context=getApplicationContext();
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyBroadcastReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60, alarmIntent);
This above is in the main method. Now i created a reciever class
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Calendar c = Calendar.getInstance();
hour=c.get(Calendar.HOUR_OF_DAY);
minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
minochaDevicePolicyManager.resetPassword(str,0);
}
}
This doesnt work. Why
I want the onReceive to run every minute. Is the code fine?
You have to add a receiver within your AndroidManifext.xml to receive the alarms.
<manifest ...>
<application ...>
...
<receiver android:name=".MyBroadcastReceiver" />
</application>
</manifest>
Related
I am trying to set an alarm within the Fragment.
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getService(getActivity(), 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 23);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 3600, pendingIntent);
And my AlarmReceiver class is:
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "MainFragment";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
Toast.makeText(context, "I'm running", Toast.LENGTH_LONG).show();
}
}
This log and toast are never shown.
In my AndroidManifest i have put
<receiver android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true"></receiver>
Am I missing something? This is my first project in Android so its probably some rookie mistake.
Here is example which is working TESTED:
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this.getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 30);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 3600, pendingIntent);
If it doesn't work I can send you the working project I made.
You're using PendingIntent.getService(...), rather than the BroadcastReceiver equivalent, PendingIntent.getBroadcast(...). Which is likely the issue.
Make sure that if you set the alarm once (like on App first launch) and while waiting you make some changes in the code and install the App again your pending intent not active anymore, so you need to set the alarm again.
I have a code in which alarm manager starts a service. I have to cancel it with the specified time using a second alarm. Not a single solution that I've looked at works. My code is as follows:
void startAtInterval(int fromTime, int fromTimeMinute, int toTime, int toTimeMinute, int id1, int id2) {
// start alarm
AlarmManager alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, fromTime);
calendar.set(Calendar.MINUTE, fromTimeMinute);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
// stop alarm
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent1 = PendingIntent.getService(getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
stopService(intent);
alarmMgr1.cancel(alarmIntent1);
}
I used FLAG_UPDATE_CURRENT and FLAG_CANCEL_CURRENT. I also tried to stopservice as I show in my code. I'm passing time from a configuration screen. I know it works because first alarm is always fired.
You should have the second alarm which cancels the service fire a BroadcastReceiver which then stops the service. This will ensure that the alarm will successfully stop the service under any circumstances, such as the app being closed.
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intentCancelService= new Intent(getApplicationContext(), StopServiceReceiver.class);
PendingIntent alarmIntent1 = PendingIntent.getBroadcast(getApplicationContext(), StopServiceReceiver.REQUEST_CODE, intentCancelService, PendingIntent.GoTestAlarmReceiver);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
Then make your BroadcastReceiver:
public class GoTestAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 123123; //whatever code just unique
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, YourServiceClassHere.class);
context.stopService(i);
}
}
Make sure to declare the receiver in your manifest:
<receiver
android:name=".StopServiceReceiver"
android:enabled="true"
android:process=":remote" />
To stop any alarm manager you have to use this:
Intent intentS = new Intent(ctx,YourService.class);
intentS.addCategory("SOMESTRING_AS_TAG");
PendingIntent senderS = PendingIntent.getService(ctx, NDX, intentS, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(senderS);
senderS.cancel();
//and this
PendingIntent senderSNew = PendingIntent.getService(ctx, NDX, intentS, 0);
am.cancel(senderSNew);
senderSNew.cancel();
where NDX is the same as started. That is 0 in your case. Or, much better, change your NDX to a some random contant number.
to stop:
Intent intent = new Intent(ctx,YourService.class);
intent.addCategory("SOMESTRING_AS_TAG");
ctx.stopService(intent);
I have a receiver inside a service as i need the scheduled alarm to work even when the activity is destroyed. This is what i have done.
/**
* Created by rishabh on 14/2/16.
*/
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
String LOG_TAG="DevicePolicyAdmin";
Log.v(LOG_TAG, "Service Started");
MainActivity.minochaDevicePolicyManager.resetPassword(str, 0);
}
}
}
And to trigger the receiver the scheduling alarm is here
Intent intent3=new Intent(MainActivity.this,MyService.class);
startService(intent3);
Intent intent2 = new Intent(MainActivity.this, MyService.MyReceiver.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent2, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 60 * 1000, pintent);
The onReceive method in the MyService class only executes once. why? What could be the issue. Please help
Try moving MyReceiver to an independent file as public class and use this code to start.
Intent intent2 = new Intent(getApplicationContext(), MyReceiver.class);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent2, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 60 * 1000, pintent);
Update 1 :
This may help you -How to repeat my service using alarm manager?
Update 2 : Check this too- Android - Periodic Background Service - Advice
you need to register it in service as follows,
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
filter.addAction("SOME_OTHER_ACTION");
context.registerReceiver(receiver, filter);
Also in onReceive method you need to check for the action of broadcast receiver fired for.
Hope this will help you.
One of your problems is that your getting a service using the intent which use the broadcast receiver. Start changing this:
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent2, 0);
For this:
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent3, 0);
What I'm trying to do; the user picks a date he wants to be notified at with DatePicker, and then I add the name, the id, the release date and the alertTime (The time in milliseconds converted from the user's chosen time) as an entry in the alarms database called myAlarmsDB, which is simple SQL. And when it gets called by the OnReceive() method I delete the entry from the database, all is good except when I close my device; the alarms don't get restored and makes my app crash with no stack-trace. Any idea what might be the problem?
public class AlertReceiver extends BroadcastReceiver {
String name = "";
int id = 0;
String releaseDate = "";
// Called when a broadcast is made targeting this class
#Override
public void onReceive(Context context, Intent intent) {
Intent intActivity = new Intent(context, MainActivity.class);
intActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intActivity);
if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Toast.makeText(context, "BOOT" , Toast.LENGTH_LONG).show();
// Set the alarm here.
Intent alertIntent = new Intent(context, AlertReceiver.class);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
for (Alarm alarm : MyApp.myAlarmsDB.getAllData()) {
alertIntent.putExtra("id", Integer.parseInt(alarm.get_id()));
alertIntent.putExtra("name", alarm.get_name());
alertIntent.putExtra("releaseDate", alarm.get_releaseDate());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, Integer.parseInt(alarm.get_id()), alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, Long.valueOf(Integer.parseInt(alarm.get_alertTime())), pendingIntent);
}
}
id = intent.getIntExtra("id", -1);
name = intent.getStringExtra("name");
releaseDate = intent.getStringExtra("releaseDate");
//delete from database
MyApp.myAlarmsDB.deleteFromId(String.valueOf(id));
}
}
How I set the alarms
public void setAlarm(View view) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, yearDate);
cal.set(Calendar.MONTH, monthDate);
cal.set(Calendar.DAY_OF_MONTH, dayDate);
long alertTime = cal.getTimeInMillis();
Intent alertIntent = new Intent(this, AlertReceiver.class);
// store id
alertIntent.putExtra("id", mainId);
alertIntent.putExtra("name", name);
alertIntent.putExtra("releaseDate", releaseDate);
Alarm alarm = new Alarm(String.valueOf(mainId), name, releaseDate, String.valueOf(alertTime));
MyApp.myAlarmsDB.addAlarm(alarm);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, mainId, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
}
Permissions:
<receiver android:name=".AlertReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
I am working in a Android application in which i want to show alert during shift change,Let say after every 8 hrs. How can I do it?
I have tried a lot, All are working with some major problem. Can i get a tutorial or tip how i can do it. i am giving what i have tried
public class ShiftConfirmService 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)
{
super.onStart(intent, startId);
Intent intent1 = new Intent(this, ShiftAlert.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
You can use ALARM MANAGER
Also there are some tutorials on it as follows
1)http://www.techrepublic.com/blog/android-app-builder/use-androids-alarmmanager-to-schedule-an-event/
2)http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html
3) You can try this code snippet for test of 24 hrs
Intent myIntent = new Intent(ThisApp.this , myService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent); //set repeating every 24 hours
4)http://learnandroideasily.blogspot.in/2013/05/android-alarm-manager_31.html
5)http://khurramitdeveloper.blogspot.in/2013/06/android-alarm-manager-to-start-service.html
set the following code in the activity where you are starting your service:
Intent myIntent = new Intent(ThisApp.this , myService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 8*60*60*1000 , pendingIntent); //set repeating every 8 hours
One more thing, you need to make a receiver which starts your service if your device is switched off. For that you also need to make few changes in Android manifest file also.
public class MyScheduleReceiver extends BroadcastReceiver {
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 300;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, YourService.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar cal = Calendar.getInstance();
service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 8*60*60*1000, pending);
// service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
// REPEAT_TIME, pending);
}
}
Android Manifest File:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.fleetcare.MyScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You can also use pending intent for particular time.
Intent intent = new Intent(this, NotificationReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
For more Android Notifications - Tutorial