Currently I am working on BroadcastReceiver, Service & AlarmManager in Android to developed one of functionality in my project. I need to schedule some task at particular time on particular day.
For E.g :-
Monday – 09:00 AM & 05:00 PM
Tuesday – 09:00 AM & 05:00 PM
Wednesday – 09:00 AM & 05:00 PM
Thursday – 09:00 AM & 05:00 PM
Friday – 09:00 AM & 05:00 PM
Saturday – 10:00 AM & 10:00 PM
Sunday – 10:00 AM & 10:00 PM
What i have done till now is created one activity & broadcastreceiver. On click of button, after every 60seconds broadcast receiver will be called. Here is my code snippet. But i want to schedule my task according to the week that i have described above. Can anyone please kindly help me how can i schedule the task like above.
Code :-
public class AlarmDemoActivity 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(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
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();
}});
}
}
BroadcastReceiver :-
public class MyScheduledReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
/*Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);*/
System.out.println("Make Phone Silent");
}
}
All suggestion and tips are welcomed.
I will give the idea for this at a very high level.You will have to figure out the coding your self:
1.Save the user preferences in shared preferences(which I presume you are already doing)
2.Schedule the first alarm using the set method of Alarm Manager
Refer this for details on this method.
3.When that alarm goes off,again schedule the next alarm using the next time period in Shared Preferences,again using the set method