Recommended method of starting a scheduled activity on start up? - android

Im trying to make an scheduled activity go off every hour or so, all working in the background.
Right now i have a BroadcastReceiver that picks up when the device is booted.
The BroadcastReceiver creates a PendingIntent to an activity (Called AlarmController) that creates has all necessary methods that i need for making the scheduled activity to go off.
How ever, this doesnt seem to work.
This is how my BroadcastReciever class onReceive{} looks like and is indentical to my main activity onCreate{}(Only for testing)
Intent intent = new Intent(serviceactivirt.this, AlarmController.class);
PendingIntent sender = PendingIntent.getActivity(serviceactivirt.this, 0, intent, 0);
try {
sender.send();
} catch (CanceledException e) {
Toast.makeText(getApplicationContext(), "FEJLSAN", Toast.LENGTH_LONG).show();
}
This actually works, except that my app crashes at launch, but the scheduled activity is working...
Any ideas? Is this "The way to do it" or is there a more recommended way?
Cheers!
Solution:
Instead of having a BroadcastReciever calling an Activity, i made the BroadcastReciever starting a Service. And changed my Activity to a Service, programmaticly and in manifest.
Works great!

Im trying to make an scheduled activity go off every hour or so, all working in the background.
Please allow users to configure other options, such as using a Notification, rather than being interrupted by an activity taking over the foreground.
Right now i have a BroadcastReceiver that picks up when the device is booted.
You would only need that to set up an AlarmManager schedule for your hourly events. Your PendingIntent for the AlarmManager could be one you obtain via getActivity().
How ever, this doesnt seem to work.
If you want to start an activity, call startActivity(). Do not create a PendingIntent, then immediately send() the PendingIntent.
Also, get rid of getApplicationContext() and simply use this.
except that my app crashes at launch
Use adb logcat, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look at the stack trace associated with your crash.

Related

Android - Not able to start multiple activities from background

I am facing a problem.
This is the code I have in my BroadcastReceiver extender class:
#Override
public void onReceive(Context context, Intent intent) {
// other
Intent myIntent = new Intent(context, ShowMessageActivity.class);
myIntent.putExtra(Utils.SHOW_MESSAGE_OPTION, messageToDisplay);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(lockScreenMessage);
}
which starts a new activity when a broadcast is raised.
When the application is in foreground and receives a broadcast, it starts a new Activity as many times as the code executes, but it is not the case when the app is in background. In that case it starts an Activity only once, and not each time a broadcast is received. Why? Is it possible to fix that?
that very depends on what do you expect in that receiver, is it any system-side call (declared in manifest) or your own? who an when calls it, thats very important
starting Android 10 there are some restrictions for starting Activity from onReceive, check out official DOC. basically you shouldn't start any Activity from there, and when it works for you I bet it works only for few secs after PendingIntent creation. check out exceptions list under link above, possible reasons would be:
The app has an activity in the back stack of an existing task on the Recents screen.
The app has an activity that was started very recently.
The app called finish() on an activity very recently.
you may check out your code on some emulator with Android 9, all your broadcast calls should work "always"

Best way to notify user of an alarm

So, I seem to have fallen down a rabbit hole trying to figure out the best way to notify a user of an alarm going off.
Basically, I want some kind of notification/dialog to come up at a certain time, and it should come up no matter what the user is doing, and block further use until acted upon (dismissed or otherwise).
Right now, I have an AlarmManager, and the BroadcastReceiver that is registered with it starts a new service.
Every time I thought I was heading in the right direction, I hit a problem where someone online had a similar issue, and was told "don't do it that way." (Having a service create/show an AlertDialog, for instance.)
I was hoping someone could give me a brief list of what their recommendation would be; I don't need code (at least I shouldn't), just some high level abstraction.
Go with Notification, which plays a sound perhaps, that would pull your user's attention to your notification, just like the default alarm does.
And make the notification an ongoing one. Which can't be removed by the user, until and unless some action is performed to change the state of the notification.
Android: How to create an "Ongoing" notification?
Dialogs for this situation would be annoying for me. The docs also suggest not to use them in these scenarios.
Have a look at this Sample Open Source Project
I did it in this way and it work fine for me.
Create a class and Call it something like ScheduledService it extends IntentService, in this class you'll do what you want to do when alarm goes off.
public class ScheduledService extends IntentService {
public ScheduledService() {
super("My service");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do something, fire a notification or whatever you want to do here
Log.d("debug", "Ring Rind !");
}
}
then in you activity to start the alarm use the following:
AlarmManager mgr = (AlarmManager) YourActivity.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(YourActivity, ScheduledService.class);
PendingIntent pi = PendingIntent.getService(YourActivity, 0, i, 0);
mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + PERIOD, pi);
Which PERIOD is after how much milliseconds you want the alarm to goes off.
To cancel stop the timer and cancel the alarm use:
if (mgr != null)
mgr.cancel(pi);
Finally for all this to work you need to register your ScheduledService class as a Service.
In your manifest add this tou your application:
<application
... />
...
<service android:name=".ScheduledService" >
</service>
</application>
This way the Android OS will take care of firing the alarm when it's time. even if other application is running or even if your app process is terminated.
Hope this help.
Regards.
Just a crazy idea: Create an activity and set it's theme to be fullscreen with no title bar and a button to stop the alarm maybe, instead of doing a notification just make an intent that starts that activity "maybe you will need This" to work even when phone is locked and play some annoying sounds, "This" may help, when the activity starts. you can also override the onBackPressed() to do nothing.

Do i need to use broadcast with alarm manager?

i'm creating an alarm application, and this is the method to run the alarm :
public void startAlarm(int minuteToStart)
{
Toast.makeText(context, "Alarm Start in " + formatTime(minuteToStart), Toast.LENGTH_SHORT).show();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, minuteToStart);
Intent intent = new Intent(context, AlarmActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, idPendingIntent, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
And it run this activity after given specific time:
public class AlarmActivity extends Activity {
......
}
It works, but i see people are using BroadcastReceiver, am i doing it wrong? should i use BroadcastReceiver too? I've been searching about BroadcastReceiver but i don't get what difference it will make with my application.
Thanks.
In the general case, A--C's answer would be correct.
However, you are using RTC_WAKEUP as the alarm type. The only guarantee that we have with _WAKEUP alarms is if we use a BroadcastReceiver, then Android will ensure that the device will stay awake long enough for us to execute onReceive(). Any other type of PendingIntent -- activity or service -- has no guarantee, and it is very possible for the device to fall back asleep before the startActivity() or startService() actually occurs.
You can use AlarmManager with whatever PendingIntent is capable of (Activity, service, Receiver), though, it is usually used with Receivers - taks executing in the future usually are small and don't need an Activity to run in since the user doesn't need something popping up.
A Receiver isn't an Activity, so it does not have a UI and it has a processing time limit of about 10 seconds, so make sure to be quick. If you require a UI to be shown at a specific time, stick with an Activity, but usually this isn't the case unless it's something like an Alarm Clock app that the user has to see). If you have something like a small behind the scenes operation, go for a Receiver. The Receiver's onReceive() gets a Context passed to it so it can do anything a Context can.
Just keep in mind you will have to change the PendingIntent.getActivity() call to whatever else you decide to use if it's not going to be an Activity.
So it all depends on what you want to do.
You don't have to use a BroadcastReceiver. It's just generally frowned upon (in most cases) to steal focus and launch an Activity from the background without user interaction. There are certainly valid use cases though. If you intend to launch an Activity immediately anyway, doing that directly instead of via BroadcastReceiver is perfectly valid.

Android addProximityAlert for all application

I want show Activity when device enter the fixed zone. I have startActivity in recivier(GpsAlarmRecivier). Code below works, but when I close Activity, it crash. I know it' s because i must unregister recivier.
But I want use addProximityAlart for all application, even after close my activity(for example, move to previous). Is it possible ?
Intent myIntent = new Intent("gpsup.namespace.ProximityAlert");
PendingIntent proximityIntent = PendingIntent.getBroadcast(cxt, 0, myIntent, 0);
locationManager.addProximityAlert(records.get(pos).x, records.get(pos).y, records.get(pos).r,
-1, proximityIntent);
IntentFilter filter = new IntentFilter("gpsup.namespace.ProximityAlert");
actv.getApplicationContext().registerReceiver(new GpsAlarmReceiver(), filter);
I want use addProximityAlert, even if I close activity, when i created recivier. Thanks for any advices.
I don't believe that there is a way to directly register a system GPSBroadcastReceiver in your application. If that was the case you could just put it in your manifest and it'll get resolved when an update comes out and then you can fire off you custom intent after performing your checks.
I believe that is actually the reason why they don't allow it (I may be wrong). It would be problematic if every application was woken up when a GPS update came out. They would be spanking the battery in the background.
A suggestion that I can give is to create a Service that listens for your GPS updates and then Broadcasts your intents. While you can have it running in the background forever, it certainly has a longer life cycle than an Activity does.

how to pop up alarm even when the application is closed

I'm developing a location based alarm which is an Android application.
All the coding part has been done.
But the alarm alert dialog is not displaying when the application is closed.
Please help me, I'm trying to pop up the alarm even when user is using another application or is in the home screen.
The code of my alarm at the moment is shown below:
final MediaPlayer mp = MediaPlayer.create(LocAlarmProject.this, R.raw.airtel);
mp.start();
// LocAlarmProject.this below is what's causing the problem:
final AlertDialog.Builder builder=new AlertDialog.Builder(LocAlarmProject.this);
builder.setTitle(disp_title);
builder.setMessage(disp_desc);
builder.setIcon(R.drawable.alarm);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mp.stop();
}
});
builder.show();
I am pretty sure you are looking for Service.
Copied and Paste:
A Service is an application component representing either an
application's desire to perform a longer-running operation while not
interacting with the user or to supply functionality for other
applications to use. Each service class must have a corresponding
declaration in its package's AndroidManifest.xml. Services
can be started with Context.startService() and Context.bindService().
Use Notification service to keep track of the status.....visit......http://developer.android.com/guide/topics/ui/notifiers/notifications.html
The proper way to do this requires a few steps. Sorry, it's not trivial if you haven't done it before:
First, you're going to use Android's built-in AlarmManager to schedule the time you want your app to be activated. You schedule a new alarm with the time to wake up and a PendingIntent.
Second, create your PendingIntent that's used to activate your app for the time to show the alarm.
Third, you can handle this Intent several ways, the most common is to create a class that extends BroadcastReceiver to receive the Intent. This class is notified when it's time to show the alarm. The Intent that you created and put inside your PendingIntent is passed to its onReceive() method. You pass this information to your app to display the alert dialog. --- You can alternatively just register your main app to receive the Intent instead, then override the onNewIntent(Intent) method in your Activity.
Four, register your BroadcastReceiver in your AndroidManifest.xml file. This is also the place to register this receiver to listen for the Intent you created. You do this using the <intent-filter> tag.
Five, (optional) if you want your alarm to display even if the phone is asleep, and you want to make sure it doesn't go back to sleep before the user acknowledges the alarm, you'll need to obtain a WAKE_LOCK to do so.
The reason this is preferable to using a Service is it doesn't consume resources just to wait for the alarm, and also it still works if Android decides to kill your app free up memory. Good luck and happy coding!

Categories

Resources