I am developing an app built on this example: https://github.com/xamarin/mobile-samples/tree/master/BackgroundLocationDemo
The example works and the location updates are coming in as expected. However, Android keeps showing an notification that the service is running and draining battery. Now, all my users have a defined working schedule (list of Start to End DateTime per day e.g 8am-1pm, 4pm-8pm), and I want that the service is only running between those working times. This means that I need to start/stop the service whenever the schedule says the user is working or not.
I've asked this question before but wondering if anyone figured out an efficient and solid way to achieve this type of service that is operating from a time schedule?
You can use AlarmManager to execute a task in specific time.
For example, I want my task running at the 10:51 am every day, I can use following code to execute it.
public static void startAlarmBroadcastReceiver(Context context)
{
Intent _intent = new Intent(context, typeof( AlarmBroadcastReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, _intent, 0);
AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
// Remove any previous pending intent.
alarmManager.Cancel(pendingIntent);
Calendar cal = Calendar.Instance;
cal.Set( CalendarField.HourOfDay, 10);
cal.Set(CalendarField.Minute, 51);
cal.Set(CalendarField.Second, 0);
alarmManager.SetRepeating(AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);
}
Here is code about AlarmBroadcastReceiver.
[BroadcastReceiver(Enabled = true, Exported = false)]
public class AlarmBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
}
}
Do not forget to add following permissions.
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
Here is running gif.
Related
I am trying to set an alarm in the alarm clock with an intent. I am using an Android One Phone (which has the unmodified OS) and have the Clock app installed (which came pre-installed) which allows setting alarm. Setting an alarm has worked in the past when I had used an AlarmManager and PendingIntent when I had to set the alarm in the background. That shows that my Clock app can respond to AlarmClock intents. But now when I am trying to send an intent from the foreground of my app, it says:
No apps can perform this action.
This is not from the stack trace, but a popup which is shown to users to choose which Clock app to choose to set the alarm (or which app to use in general for an intent)
Here's the Activity's onCreate() code where I am calling it:
public class MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Utils.setAlarm(this, Utils.getLDT(epochTime).plusHours(8));
}
}
Here's the Utils#setAlarm function that sends the intent:
public class Utils {
public static void setAlarm(Context context, LocalDateTime alarmTimeDT) {
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
intent.putExtra(AlarmClock.EXTRA_HOUR, alarmTimeDT.getHour());
intent.putExtra(AlarmClock.EXTRA_MINUTES, alarmTimeDT.getMinute());
intent.putExtra(AlarmClock.EXTRA_MESSAGE, "Good Morning");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
...
}
This is the additional code that was used in the past for the same device and same Clock app. This is for cancelling an already set alarm, but the code used to set the old alarm was similar except for the cancelling part:
//cancel old alarm
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getActivity(
this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
if (alarmIntent != null) {
alarmMgr.cancel(alarmIntent);
} else {
Log.i(TAG, "intent is null");
}
What am I doing wrong? Any help appreciated.
The below comments is just questioning and asking for more clarification on the question, which were done as asked for. So you may skip reading them
No apps can perform this action.
This happens when you don't have the required permission to set the alarm.
From AlarmClock reference:
Applications that wish to receive the ACTION_SET_ALARM and ACTION_SET_TIMER Intents should create an activity to handle the Intent that requires the permission com.android.alarm.permission.SET_ALARM.
Request the SET_ALARM permission:
<mainfest
...
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
</manifest>
i am using AlarmManager class for setting Alarms it is working fine.
But if i set alarm like 9pm and current time is 8pm and i changed the system time to 10pm
then alarm 9pm alarm start automatically. so to solve this issue
i have searched so much but did not found any good answer
Please help
here is my code for alarm setting
final int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("requestCode", id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 2*60*1000, pendingIntent);
One of the options is to store all set alarms in database, then create a BroadcastReceiver which will listen for ACTION_TIME_CHANGE action. When user changes time it will be triggered. Then create a IntentService which will be responsible for resetting alarms. In this service class:
Read db and identify all passed alarms.
Cancel passed alarms
Set alarms for next day
Your code may look like as below:
In your Manifest:
<uses-permission android:name="android.permission.ACTION_TIME_CHANGE"/>
and below activities:
<receiver android:name=".TimeChangedReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
<service android:name=".RestartAlarmsService"/>
Create class "TimeChangedReceiver" inside of which:
public class TimeChangedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("android.intent.action.TIME_SET".equals(intent.getAction())) {
Intent i = new Intent(context, RestartAlarmsService.class);
ComponentName service = context.startService(i);
}
}
}
Create "RestartAlarmsService" class inside of which:
public class RestartAlarmsService extends IntentService {
public RestartAlarmsService() {
super("RestartAlarmsService");
}
#Override
protected void onHandleIntent(Intent intent) {
// read db here
// then cancel passed alarms
// reset them to next day
}
}
You can find many tutorials on how to use Databases and implement it in your code. Hope my answer is somehow helpful.
yes it will give you broadcast, as your pending intent object is still attached to that event while you change time that is greater than you alarm firing time.
solution- validate your condition while you receive broadcast from alarm manager
Currently I work on a reminder android app, since it remind people to take the pill , so it is really important for the system not missing the alarm.
I found some tutorial and create the code like this:
setTimer.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
GregorianCalendar date = new GregorianCalendar(2014,5,4,15,4); // Month start at 0 , meaning January is 0
long dateTime = date.getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(ctx, AlarmReceiver.class);
alarmManager.set(AlarmManager.RTC_WAKEUP, dateTime, PendingIntent.getBroadcast(ctx, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
});
Mainfest
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<receiver android:name=".Listener.AlarmReceiver" />
Receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
}
The problem is I wonder will the alarm invoke even I haven't open the app. The only case missing the alarm is when the user turn off the device? Thanks
You can start a background service through your app which takes care of setting up alarms and firing them even when your app is not opened or in the foreground. Here's a tutorial on services ----> http://www.vogella.com/tutorials/AndroidServices/article.html
In my app I have SQLite database that has one table with date rows in milliseconds. I would like to have a notification shown every day IF 30 days has passed since the last date value stored in my database. A service seems to be a good way to accomplish this check up.
I ran into Commonsware's WakefulIntentService and thought it could be the answer but I really don't know how should I implement it. In the demo it starts a service after 5 minutes since boot is complete which is just fine but what do I need to add to get it also start at every noon. (... but only to show one notification / day, not both, as from boot and regular daily check up)
I know this could be solved using AlarmManager but really don't know how. So, the help I need is to give me some samples / key points to get the service start on every boot and/or every day without app running.
thanks
Android alarmmanager is your answer. use it with a broadcast receiver which also resets the alarms on phone wake.
Now with code example:
Setting alarm inside a method:
Intent intent = new Intent(context, AlarmReceiver.class);
intent.setAction("packagename.ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Receiver for your interval:
public class AlarmReceiver extends BroadcastReceiver {
private final String SOMEACTION = "packagename.ACTION"; //packagename is com.whatever.www
#Override
public void onReceive(Context context, Intent intent) {
Time now = new Time();
now.setToNow();
String time = FileHandler.timeFormat(now);
String action = intent.getAction();
if(SOMEACTION.equals(action)) {
// here you call a service etc.
}
Receiver for resetting alarms whenever phone has been shut down.
public class AlarmSetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// get preferences
SharedPreferences preferences = context.getSharedPreferences("name_of_your_pref", 0);
Map<String, ?> scheduleData = preferences.getAll();
// set the schedule time
if(scheduleData.containsKey("fromHour") && scheduleData.containsKey("toHour")) {
int fromHour = (Integer) scheduleData.get("fromHour");
int fromMinute = (Integer) scheduleData.get("fromMinute");
int toHour = (Integer) scheduleData.get("toHour");
int toMinute = (Integer) scheduleData.get("toMinute");
//Do some action
}
}
}
Manifest very important, this is added under application:
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="packagename.ACTION"/>
<action android:name="packagename.ACTION2"/>
</intent-filter>
</receiver>
<receiver android:name="AlarmSetter" >
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Also in order for this to work you need to add permission to receive the boot Broadcast in the manifest with following line:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Hope this cleared things up, if any errors plz tell.
Edit (added alarmsetter example):
public class AlarmSetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Do your stuff
}
}
This answer seems pretty old.
Now, I would totally recommend people to check out SyncAdapter framework provided by Google.
It is custom made for such things.
Here's the link: https://developer.android.com/training/sync-adapters/index.html
In the demo it starts a service after 5 minutes since boot is complete which is just fine but what do I need to add to get it also start at every noon.
Change the initial time of the setRepeating() call. The example shows one minute from now -- you would need to do the calculations to determine when the next noon is.
You can see an example of that sort of calculation in this OnBootReceiver from a different sample project. Here, I am setting up the alarm to go off every day at a user-specified time.
I've poured through a dozen tutorials and forum answers about this problem, but still haven't been able to get some working code together. I'll try to keep the question straightforward:
How do you use AlarmManager (in the Android API) to start an Activity at a given time? Any solution to this problem will do.
My latest attempt to achieve this is below.
(Imports omitted. I expect MyActivity to start 3 seconds after the program is opened, which it doesn't. There are no error messages to speak of.)
public class AndroidTest2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = this;//.getApplicationContext();
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // CORRECT
Intent intent = new Intent(context, myReceiver.class); // CORRECT
PendingIntent pending = PendingIntent.getBroadcast( context, 0, intent, 0 ); // CORRECT
manager.set( AlarmManager.RTC, System.currentTimeMillis() + 3000, pending ); // CORRECT
setContentView(R.layout.main);
}
}
public class myReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent i=new Intent(context, myActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
public class myActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("", "Elusive success");
setContentView(R.layout.main);
}
}
Any advice would be appreciated.
Please note: I've got myReceiver in the manifest already
In case someone else stumbles upon this - here's some working code (Tested on 2.3.3 emulator):
public final void setAlarm(int seconds) {
// create the pending intent
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
intent, 0);
// get the alarm manager, and scedule an alarm that calls the receiver
((AlarmManager) getSystemService(ALARM_SERVICE)).set(
AlarmManager.RTC, System.currentTimeMillis() + seconds
* 1000, pendingIntent);
Toast.makeText(MainActivity.this, "Timer set to " + seconds + " seconds.",
Toast.LENGTH_SHORT).show();
}
public static class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("-", "Receiver3");
}
}
AndroidManifest.xml:
<receiver android:name="com.example.test.MainActivity$AlarmReceiver" >
</receiver>
Issues with BenLambell's code :
EITHER:
Move the receiver to it's own .java file or
make the inner class static - so it can be accessed from outside
Receiver is not declared correctly in the manifest:
if it's an inner class in MainActivity use:
<receiver android:name="package.name.MainActivity$AlarmReceiver" ></receiver>
if it's in a separate file:
<receiver android:name="package.name.AlarmReceiver" ></receiver>
If your intention is to display a dialog in the receiver's onReceive (like me): that's not allowed - only activities can start dialogs. This can be achieved with a dialog activity.
You can directly call an activity with the AlarmManager:
Intent intent = new Intent(MainActivity.this, TriggeredActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + seconds * 1000, pendingIntent);
How do you use AlarmManager (in the Android API) to start an Activity at a given time?
Supply a PendingIntent to the set() call that identifies the activity to start up. Or, do what you're doing, which should work just fine.
This sample project is a bit elaborate, because it's 19 tutorials deep into one of my books, but if you look at classes like EditPreferences, OnBootReceiver, and OnAlarmReceiver, you will see the same basic recipe that you're using above. In this case, I could have just used a getActivity() PendingIntent, but the tutorial after this one gives the user a choice of launching an activity or displaying a Notification, so a BroadcastReceiver makes more sense.
Look for warnings in addition to errors in LogCat. Most likely, your receiver or activity is not in your manifest.
Note that popping up an activity out of the middle of nowhere is generally not a good idea. Quoting myself from the book in question:
Displaying the lunchtime alarm via a full-screen activity certainly works,
and if the user is looking at the screen, it will get their attention. However,
it is also rather disruptive if they happen to be using the phone right that
instant. For example, if they are typing a text message while driving, your
alarm activity popping up out of nowhere might distract them enough to
cause an accident. So, in the interest of public safety, we should give the user an option to
have a more subtle way to remind them to have lunch.
add this in your android mainifest file and it will hopefully work
<activity android:name=".MyReceiver" />
<receiver android:name=".MyReceiver"> </receiver>
In my experience you can achieve this without broadcast receiver, just use PendingIntent.getActivity() instead of getbroadcast()
private void setReminder(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar startTime = Calendar.getInstance();
startTime.add(Calendar.MINUTE, 1);
Intent intent = new Intent(ReminderActivity.this, ReminderActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(ReminderActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, startTime.getTimeInMillis(), pendingIntent);
}
I've tested this code on android O but I'm not sure about other android versions please inform me if this doesn't work on any other android version.
Main Problem : if you close completely you're app and expect to start you're activity after 3 seconds, you wrong. because when you close you're app , you're app cant receive broadcast, for solve this problem use services instead of broadcasts.
Point: when you're service would ran ,you cant start your activity if your app wouldn't in foreground.
Solution: I think when your service started you can again set Alarmmanager to start your activity with PendingIntent for just now.
Remember :
When you create your intent for pass it to pendingIntent add the FLAG_ACTIVITY_NEW_TASK to it.
For this PendingIntent use PendingIntent.getActivity() method and for the first PendingIntent use PendingIntent.getService() method.
I hope this help you.
I had this problem too long ago to know which answer is correct, but thank you to everyone for their responses. I'm self-answering so the question isn't still open.
According to Java convention class name begin with Capital letter.So change your
"myReceiver" to "MyReceiver" and "myActivity" to "MyActivity".
Then add your receiver in the manifest file like the below.
<application
------------
<receiver android:name="MyReceiver"></receiver>
---------------------
</application>
you are not sending any broadcast for the receiver to receiver and further more it lokks like u want a splash screen or something like that for that purpose u can start a new thread wait for some sec then start ur activity in that and for that time period u can do what ever u want on the UI thread ...