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
Related
I have a button it should work according to time from 09.00 Am to 04.00 pm and rest of time it should not work.
I am developing an app. I am new in android. I have three buttons namely register, events, gallery.
When I click register button it should work according to time mentioned above.
if the user click register on that time it should pass on to the next activity and rest of times the button click action should not work.
check for class AlarmManager
on app start create AlarmManage class service with
time gap current to desable/enable time in milisecond.
public class MyReceiver extends BroadcastReceiver {
private static final int PERIOD = 1200000;//20*60*1000; 20 minutes
#Override
public void onReceive(Context ctxt, Intent i) {
scheduleAlarms(ctxt);
}
public static void scheduleAlarms(Context ctxt) {
AlarmManager mgr =
(AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, AuthenticateService.class);
PendingIntent pi = PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
Sorry if i didn't write a suitable title for my problem.
I am developing an android game in which i had to start count down timer from 10 minutes. The value to be stored in textView
Now my textView is showing the countdown value i.e it starts from 09:59 and decreasing second by second but obviously when i close the application and then restart its gone. This should be saved via shared preference but Iam confused how to used shared preference in it.
i.e. if i close the app when 07:45 minutes left and preference is saved then when i will return and restart the app after 2 minutes then it should show 05:45 minutes left then how can i get that? because if I subtract the countdown time from system time then it may be not the result that i wanted because system time is in hour format and iam using minute and second only.
Here is the code before oncreate
MyCounter timer = new MyCounter(600000,1000);
private static final String FORMAT = "%02d:%02d";
and this is what iam using to get the countdown timer in textview
public class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
datetime.setText("Timer Completed,Now you can play");
}
#Override
public void onTick(long millisUntilFinished) {
datetime.setText(""+String.format(FORMAT,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
}
Any link to specific code and shared preference example using countdown will help me a lot
Create an alarm set method, this is used to set/start alarm.
public void SetAlarm(Context context){
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TenMinuteTimer.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),10*60*1000, pendingIntent);
}
Cancel the alarm, this method is used to remove the alarm once it has been reached
public void CancelAlarm(Context context){
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TenMinuteTimer.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.cancel(pendingIntent);
}
Save when the alarm completed those 10 minutes:
public class TenMinuteTimer extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//Save, timer has completed.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
prefs.edit().putBoolean("timerCompleted", true).commit();
//cancel the Alarm, no need for repeating (right?)
CancelAlarm(this);
}
Add to your Manifest.XML:
<receiver
android:name=".TenMinuteTimer"
android:enabled="true"
android:process=":remote">
</receiver>
Start/Set your alarm whenever you want, by calling the SetAlarm(this) method
Check , when a user starts your application again just check if timer has completed by adding to your onCreate() :
Boolean usetTimerCompleted = prefs.getBoolean("timerCompleted", false); //False if not yet saved (first time), or timer is not yet completed
if (usetTimerCompleted){
// User Timer is completed, now do something
}
This should work,
If I did something wrong, please edit my post, or comment below.
I didn't test this out!
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 have an alarm service that works with alarm manager. it's works correctly when you set alarm for later. but when you set it for past ( you want to alert you tomorrow) it gone crazy and alert several times instead of once and finally wont work tomorrow.
some one plz help me on this.
i do like this: I have a alarm class. when i create it, so it make an pending intent that run a service with alarm manger. and the service will open my activity.
is it the wrong way?
here is my alarm class:
public class MyAlarm {
private Context myContext;
private NotificationManager mNM;
private int NOTIFICATION = 10002; //Any unique number for this notification
MyAlarm(Context myAct){
myContext = myAct;
showNotification();
}
// this constractor is for cancelling alarm
MyAlarm(Context myAct, String str) {
myContext = myAct;
cancelPendigIntent();
}
private void cancelPendigIntent() {
//Intent myIntent = new Intent(myContext, MyAlarmService.class);
//G.pendingIntent = PendingIntent.getService(myContext, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//G.pendingIntent.cancel();
//G.alarmManager.cancel(G.pendingIntent);
}
private void showNotification() {
Intent myIntent = new Intent(myContext, MyAlarmService.class);
G.pendingIntent = PendingIntent.getService(myContext, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
G.alarmManager = (AlarmManager)myContext.getSystemService(Context.ALARM_SERVICE);
G.calendar = Calendar.getInstance();
int to_day= G.calendar.get(Calendar.DATE);
int to_mounth= G.calendar.get(Calendar.MONTH);
int to_year= G.calendar.get(Calendar.YEAR);
G.calendar.set(to_year, to_mounth, to_day, Integer.parseInt(G.myPref.loadString("alert_time_houre")), Integer.parseInt(G.myPref.loadString("alert_time_mins")), 0);
Log.i("LOG", "alert_time_houre="+G.myPref.loadString("alert_time_houre")+" alert_time_mins="+G.myPref.loadString("alert_time_mins"));
G.alarmManager.setRepeating(AlarmManager.RTC, G.calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, G.pendingIntent);
}
i finally find the answer.
my problem is not about alarm manager.
i set the pendig intent to a service that opens a activity. the problem was while the service is run in background it opened my activity again and again and my app go crazy. maybe i should destroy the service after her job done once.
i change it from service to broadcastreceiver and it's works correctly.
thanks for guides :)
This is my code:
public class Alarm extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
}
}
and
public final class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
By the above code i am able to get the Toast. Instead of Toast I want the Dialog to be appear after the alarm is set. Also I want to play the sound.
Any one help me please?
You cannot display a Dialog from a BroadcastReceiver or Service. You will be better served using an Activity (perhaps one using Theme.Dialog) and calling startActivity().
Bear in mind, though, that users tend to really dislike it when background stuff pops up activities unannounced. For some apps -- alarm clocks, VOIP clients, etc. -- the user may be OK with it.
There is a cool trick to do that.
Here are the steps to do it:
Place the BroadcastReceiver inside your Activity as an inner class.
Instead of adding the BroadcastReceiver in the manifest, you register yourself in the onStart() method of your Activity.
You unregister in the onPause() method of your Activity.
Inside the BroadcastReceiver you can call an Activity's method that do exactly what you ask for.