How to Autostart an AlarmManager to start a Scheduled Activity? - android

This tutorial come from android-er,
The main activity(AndroidScheduledActivity.java) start a AlarmManager to trigger BroadcastReceiver(MyScheduledReceiver.java) repeatly. In the onReceive() method of MyScheduledReceiver, it start another activity(MyScheduledActivity.java) indirectly. Such that the activity(MyScheduledActivity.java) will be start in scheduled interval.
Now I would use AutoStart to start automatically, but I was not able to write the AutoStartNotifyReceiver .
please can you give me an idea how to manage it ?
Thanks a LOT !
main activity, AndroidScheduledActivity.java :
public class AndroidScheduledActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.start);
buttonStart.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(getBaseContext(),
MyScheduledReceiver.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 interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
finish();
}});
}
}
Then BroadcastReceiver, MyScheduledReceiver.java
public class MyScheduledReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
and my problem AutoStartNotifyReceiver :
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
????????????????????
}
}
}

Your AutoStartNotifyReceiver extends BroadcastReceiver class is there because the alarms get cleared when the device resets. So, in the onReceive of this class (where you have the question marks) you need to set the alarm all over again with the same code (without, of course the finish())that you used to do it the first time in the onClick method of AndroidScheduledActivity.
Then, you need to put the following entry in your Manifest to let the system know to launch your AutoStartNotifyReceiver when the system boots up:
<receiver android:name=".AutoStartNotifyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
As well as a permission in the Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Now, this is all assuming you only have one alarm and only set it one way every time. If that is not the case than this gets a bit more complicated. But based on the little info you provided, my solution should do what you want.
Also, since you are a newcomer here just a kindly reminder: when someone provides an adequate answer to a question, the person asking the question (you) accepts the answer by clicking the checkbox next to the answer. This is so the person answering gets credit. Welcome to SO!

thanks, it works. just need to improve my java a little more. I have to add "context" don t know exactly why.
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
Intent myIntent = new Intent(context, MyScheduledReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pendingIntent);
}
}
}

Related

How do I make an action at a specific time when the phone is locked?

I have this method. The problem is that it does not work when I lock the phone. It only shows me the notification if the phone has the screen on, if I block it and I activate it only 5 minutes later (it is 9:00 p.m. and I put it on at 9:05 p.m.), nothing happens. I read this questions, but I don't know how to start it at a specific time. Thanks in advance and please don't check this question as duplicate of this question
public void startBroucast(int a,int b) {
int minutes=a;
int hours=b;
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR,hours);
c.add(Calendar.MINUTE,minutes);
Timer time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
showNotification();
}
},c.getTime());
}
You should use AlarmManager to schedule tasks in the future. Here's how you can do that:
public void startBroucast(int minutes,int hours) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,hours);
c.set(Calendar.MINUTE,minutes);
long timeInMillis = c.getTimeInMillis();
Intent notificationIntent = new Intent(getContext(),NotificationReceiver.class);
mNotificationId = 123; //the id of the notification - you can use it to
//change the notification later
PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(getContext(),mNotificationId,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,timeInMillis,pendingNotificationIntent);
}
Now, you need to create the NotificationReceiver class.
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(); //this is where you create and schedule your notification
}
}
You also need to register the BroadcastReceiver in your AndroidManifext.xml
<receiver
android:name=".util.NotificationReceiver"
android:enabled="true"
android:exported="false" />

Upload Image from IntentService when the app is closed

I'm developing an app that synchronize your local date with the cloud. So I need to check automatically, each 10 minutes, my local data to get the new camera files to upload to the cloud.
So I have used an IntentService that works only when the app is running in foreground. If I close it, my service doesn't upload anything.And I WANT MY INTENTSERVICE WORKS IN BACKGROUND with the AlarmManager.
My IntentService is declared in Manifest.xml:
<!-- Uploader and Deleter Files Service -->
<service android:name=".receiver.UploadDeleteService" android:exported="false" />
<receiver
android:name=".receiver.AlarmReceiver"
android:process=":remote" >
</receiver>
My AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.codepath.example.servicesdemo.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, UploadDeleteService.class);
context.startService(i);
}
}
My ServiceInteractor where I instance my AlarmReceiver inside AlarmManager:
public class ServiceInteractorImpl implements ServiceInteractor {
private Context context;
public ServiceInteractorImpl(Context context){
this.context = context;
}
#Override
public void launchService() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(context, AlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, AlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 10);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.getTimeInMillis(), pIntent);
}
}
My UploadDeleteService where I call to the retrofit implementation module:
public class UploadDeleteService extends IntentService implements ApiConnector.GetObjectListener {
private RemoteInteractor remoteInteractor;
public UploadDeleteService(String name) {
super(name);
}
public UploadDeleteService() {
super("UpdateDeleteService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i("SERVICE", "Service running");
remoteInteractor = new RemoteInteractorImpl(getApplicationContext());
remoteInteractor.checkNews(this);
}
#Override
public void onImageUploaded(String type, JSONObject response) {
Log.d("SERVICE", " onImageUploaded ");
//REST OF THE STUFF....
}
}
Please I need a helping hand to solve that problem. I need it works each 10 minutes although the app is closed. Thanks!
For stopped Service:
change "cal.getTimeInMillis()" to "10*60*1000"
cal.add(Calendar.MINUTE, 10); //this will add 10 minute to current time
For Stopped open app when service start:
normally it will not open your app, you need to check what happened in RemoteInteractorImpl.class
you create new instance at onHandleIntent
remoteInteractor = new RemoteInteractorImpl(getApplicationContext());
remoteInteractor.checkNews(this);

About AlarmManager and the way it is saved

I'm making an app that uses an Alarm service. I'm still learning how it works but one thing is very unclear and explained nowhere.
Say you create an Alarm when you launch your app. The alarm is saved somewhere because it needs to trigger even when your app is not running, right?
If so, how can I get this alarm when relaunching my app, so I don't create a new one everytime and have an infinity of alarms stored somewhere?
If not, how does it work? I was thinking about using a database or a json file but I have a feeling it's not necessary.
In my MainActivity class, I have this code to check if the alarm exists already (this code is obviously wrong)...
AlarmReceiver alarm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(alarm != null){
alarm.cancel();
}
alarm = new AlarmReceiver(MainActivity.this);
}
});
}
I have set a BroadcastReceiver for when the device is rebooted (as explained in the android tutorial)
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
new AlarmReceiver(context);
}
}
}
This is the AlarmReceiver class itself:
public class AlarmReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
public AlarmReceiver(Context context){
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmBroadcastReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 30);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public void cancel(){
alarmMgr.cancel(alarmIntent);
}
}
And the AlarmBroadcastReceiver that simply launches a notification (which works):
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
new NotificationMessage(context);
}
}
The alarm is saved somewhere because it needs to trigger even when your app is not running, right?
Correct.
how can I get this alarm when relaunching my app
You don't. It's a write-only API.
so I don't create a new one everytime and have an infinity of alarms stored somewhere?
Only create an alarm when it is needed, not on every run of your app.
Beyond that, use an equivalent PendingIntent to an existing alarm when calling the AlarmManager methods to replace that alarm (or using cancel() to cancel the alarm).
I was thinking about using a database or a json file but I have a feeling it's not necessary.
You need enough information in persistent storage to know what to do when the alarm goes off. You also need enough information in persistent storage to know what alarms are needed, to handle reboots, when you have to reschedule your previously-scheduled alarms.

Launching alert dialog some times work and some time it does not

i'm using below code to launch the alert dialog. This works well sometimes & some times it does not.
` Intent alarmIntent = new Intent("android.intent.action.MAIN");
alarmIntent.setClass(ct, AlertsDlgactivity.class);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Pass on the alarm ID as extra data
// Start the popup activity
ct.startActivity(alarmIntent);`
Also, few times multiple instances of dialog appears, any help on how to work on this
Without seeing all of your code, I'm not sure how your trying to accomplish this, so I am providing a simple Function to use the Alarm Manager:
public void scheduleAlarm(int year,int month,int day,int hr,int min,int sec, String message, int _id)
{
long future = new GregorianCalendar(year,month,day,hr,min,sec).getTimeInMillis();
Intent intentAlarm = new Intent(this, AlarmReciever.class);
intentAlarm.putExtra("_MESSAGE",message);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, future,
PendingIntent.getBroadcast(this, _id, intentAlarm, PendingIntent.FLAG_ONE_SHOT));
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
}
And this would be AlarmReciever.class
public class AlarmReciever extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Use this to get variables passed from Main Activity
String message = intent.getStringExtra("_MESSAGE");
//Do some stuff here
}
}
Also don't forget to add these to your Manifest:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
<receiver android:name=".AlarmReciever"/>
</application>

How to use a timer?

I want to change the background, but I want to change it using a timer. for example in the morning I have a background and evening I have another background. But I don't know what to use in Android. and if you have an example to follow. any idea?
Just to make sure I understand what you mean, do you want to:
-Change the background after a time or
-change the background at different daytimes?
To accomplish the second one, I would set a switch into your OnCreate() method (or any other place e.g. OnResume(), a button click) that looks for the Time with
Time t = new Time();
t.setToNow();
and then decides what Image to use
Here is the code which repeat the alarm every day. You will have to take out your needed code from this activity(sorry for that). You can use this code to set alarm which will repeat every day at 9am. You can add same for evening at your expected time.
public class AndroidScheduledActivity extends Activity {
/** Called when the activity is first created. */
int id = 115;
Intent myIntent;
PendingIntent pendingIntent;
AlarmManager alarmManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.start);
myIntent = new Intent(getBaseContext(), MyScheduledReceiver.class);
myIntent.putExtra("id", id);
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), id, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
buttonStart.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
setForMonday();
finish();
}});
}
public void setForMonday() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK,2);
calendar.set(Calendar.HOUR,09);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
System.out.println("Old is set# :== " + calendar.getTime());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
Here is the alarm receiver
public class MyScheduledReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// here you can add the code to change the background
System.out.println("Receiver");
}
}
Also you will have to add receiver in the manifest file.

Categories

Resources