How to use a timer? - android

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.

Related

Listen chrome custom tab progress event

I have an application using Chrome custom tabs to open some links, I need to have event each second during all the time the user stay on Chrome, or know how many time he stay on Chrome. For me the only way to do it is to use a Service. Is it possible to do it differently?
Create your YourBroadCastReceiver class as follows
public class YourBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Called every 60 seconds","called");
}
}
After starting your custom tab successfully create Alarm PendingIntent that will trigger YourBroadCastReceiver once every 60 sec.
// Retrieve a PendingIntent that will perform a broadcast
Intent repeatingIntent = new Intent(context,
YourBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, _pendingIntentId, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at 10:00 AM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
manager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60 * 1000, // repeat for every 60 seconds
pendingIntent);
after closing your custom tab never forget to cancel your PendingIntent
PendingIntent.getBroadcast(
context, _pendingIntentId, alarmIntent, 0).cancel();
For implementation of chrome custom tabs I've followed this tutorial, github link.
My solution basically rely on boolean and System.currentTimeMillis().
Step - 1 : Declare two class global variables,
private boolean isCustomTabsLaunched = false;
private long customTabsEnterTime;
Step - 2 : Set values for above to variables when launchUrl.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "FloatingActionButton");
// Launch Chrome Custom Tabs on click
customTabsIntent.launchUrl(CustomTabsActivity.this, Uri.parse(URL));
isCustomTabsLaunched = true;
customTabsEnterTime = System.currentTimeMillis();
Log.d(TAG, "customTabsEnterTime = " + customTabsEnterTime);
}
});
Step - 3 : Calculate stay time in onResume method.
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (isCustomTabsLaunched) {
isCustomTabsLaunched = false;
calculateStayTime();
}
}
private void calculateStayTime() {
long customTabsExitTime = System.currentTimeMillis();
Log.d(TAG, "customTabsExitTime = " + customTabsExitTime);
long stayTime = (customTabsExitTime - customTabsEnterTime) / 1000; //convert in seconds
Log.d(TAG, "stayTime = " + stayTime);
}
In order to make code more robust you may like to store boolean isCustomTabsLaunched and long customTabsEnterTime in preferences or database so in any case these two params get destroyed as your activity may get destroy in background if user stay for long time in chrome custom tab.

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.

I am trying to set alarm on specific time using alarm manager but alarm initiated instantly?

This is my onclick() function.this will set target alarm
SA=(Button)findViewById(R.id.button1);
SA.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(id);
}
});
}
#Override
protected Dialog onCreateDialog(int id1) {
switch (id1) {
case id:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, min,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
Calendar calnow=Calendar.getInstance();
calnow.setTimeInMillis(System.currentTimeMillis());
calnow.set(Calendar.HOUR_OF_DAY,selectedHour);
calnow.set(Calendar.MINUTE,selectedMinute);
calnow.set(Calendar.SECOND, 0);
Intent intent=new Intent(getBaseContext(),alarm.class);
PendingIntent pendingintent= PendingIntent.getBroadcast(getBaseContext(),0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calnow.getTimeInMillis(),pendingintent);
Toast.makeText(getBaseContext(), "alarm set", Toast.LENGTH_SHORT).show();
}
};
public void onReceive(Context arg0, Intent arg1) {
AlarmManager mgr = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);
Toast.makeText(arg0,"Alarm Started.....", Toast.LENGTH_LONG).show();
Here problem is that I get both toasts "alarm set" and"alarm started" as soon as I click button to set alarm before reaching target alarm.
your fault is here. so do it like that
Calendar calnow=Calendar.getInstance()
calnow.set(Calendar.HOUR_OF_DAY,selectedHour);
calnow.set(Calendar.MINUTE,selectedMinute);
calnow.set(Calendar.SECOND, 0);
if (calnow.getTimeInMillis()< System.currentTimeMillis()) {
calnow.set(Calendar.DAY_OF_YEAR, 1)
}
the problem here is, that the value from TP seems to be the current time. It would be helpful if You show more of Your code. Let me give You an example for setting alarm time with a delay of 5 seconds. Please try out this one, it´s a dirty way, I just want to explain. This is what You did:
calnow.set(Calendar.HOUR_OF_DAY,TP.getCurrentHour());
calnow.set(Calendar.MINUTE,TP.getCurrentMinute());
alarmManager.set(AlarmManager.RTC_WAKEUP, calnow.getTimeInMillis(),pendingintent);
to get a delay of five seconds, change it to
alarmManager.set(AlarmManager.RTC_WAKEUP, calnow.getTimeInMillis()+5000,pendingintent);
like I said, this is only to show which value You have to set to alarmManager. It has to be the time in milliseconds, when You want to start the alarm. For this, You have to be sure to get the right values from Your TP. So, if You want us to help You, it will be a good way to show us the complete code

How to Autostart an AlarmManager to start a Scheduled Activity?

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);
}
}
}

Help required in Alarm Application

I am new to Android. I am trying to develop an Alarm Application, which is actually a speaking clock. I just want the clock to use TextToSpeech API and speak out the greeting stuff and the current time as soon as the alarm time is ticked. The speech part is done. And now I want to implement the Alarm functionality. But Initially I am just trying to display a toast after 10 secs in order to check whether my classes are working properly. And I am not getting the desired response and I don't know why ? Following are the classes
Main Class aClockActivity
public class aClockActivity extends Activity {
/** Called when the activity is first created. */
private PendingIntent mAlarmSender;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.buttonOn);
button1.setOnClickListener(mStartAlarmListener);
Button button2 = (Button)findViewById(R.id.buttonOff);
button2.setOnClickListener(mStopAlarmListener);
}
private OnClickListener mStartAlarmListener = new OnClickListener() {
public void onClick(View v) {
// We want the alarm to go off 30 seconds from now.
//long firstTime = SystemClock.elapsedRealtime();
EditText Ehour = (EditText) findViewById(R.id.hour);
EditText Eminute = (EditText) findViewById(R.id.minute);
CharSequence CharHour = Ehour.getText();
CharSequence CharMinute = Eminute.getText();
int hour = Integer.parseInt(CharHour.toString());
int minute = Integer.parseInt(CharMinute.toString());
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.MINUTE, 1);
cal.add(Calendar.SECOND, 10);
mAlarmSender = PendingIntent.getBroadcast(aClockActivity.this,
0, new Intent(aClockActivity.this, Alarm_Broadcast.class), 0);
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), mAlarmSender);
// Tell the user about what we did.
Toast.makeText(aClockActivity.this, "The Alarm is Set",
Toast.LENGTH_LONG).show();
}
};
private OnClickListener mStopAlarmListener = new OnClickListener() {
public void onClick(View v) {
// And cancel the alarm.
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.cancel(mAlarmSender);
// Tell the user about what we did.
Toast.makeText(aClockActivity.this, "Setting off the alarm",
Toast.LENGTH_LONG).show();
}
};
Second Class Alarm_Broadcast
public class Alarm_Broadcast extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked", Toast.LENGTH_LONG).show();
}
}
Note: Just ignore the Edittext part in the OnClick() method, I'd use it later on.
Apart from the above problem there are few questions that I would like to ask.
1) How can I implement this app so that when the alarm is set, it can actually run as a service in the notification bar where the original AlarmClock runs. So that even if the app is closed its still running to invoke the alarm message at the right time.
2) I cannot show any Dialog box or can use TTS if the AlarmManager invokes a Class that extends either Service or BroadcastReciever.
3) I would appreciate if some one give me the idea to implement this app, I am sure there are many experts who would have gone through the same application.
Regards
Omayr
Here is some sample code i used in an alarm clock app hope it helps.
To set the alarm:
private void setAlarm(){
Context context = getApplicationContext();
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
myCal = Calendar.getInstance();
myCal.setTimeInMillis(TIME_THE_ALARM_SHOULD_GO_OFF_AS_A_LONG);
mgr.set(AlarmManager.RTC_WAKEUP, myCal.getTimeInMillis(), pi);
Log.i(myTag, "alarm set for " + myCal.getTime().toLocaleString());
Toast.makeText(getApplicationContext(),"Alarm set for " + myCal.getTime().toLocaleString(), Toast.LENGTH_LONG).show();
}
This goes in the onAlarmReceiver class:
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
this will start AlarmActivity whenever it needs to go off. In your case you'd put the toast and speech into the AlarmActivity.
How can I implement this app so that when the alarm is set, it can actually run as a service in the notification bar where the original AlarmClock runs. So that even if the app is closed its still running to invoke the alarm message at the right time.
Do not do this. Having a service stick around in memory 24x7 to watch a clock is a waste of RAM and will get you attacked by task killers, reducing your app's effectiveness. Please stick with AlarmManager.
I cannot show any Dialog box or can use TTS if the AlarmManager invokes a Class that extends either Service or BroadcastReciever.
Start an activity, perhaps a dialog-themed activity.
Just got the answer, whatever service, receiver, activity and etc you are using, you need to register it in your AndroidManifest.xml. Or else it wont work

Categories

Resources