How to show remaining time for alarm to ring using AlarmManager? - android

I want to know how I can show the time that is remaining for the alarm to ring. And I also want to know that how we can increment/change a variable value of different class from a different class. Suppose if I have a game where users get life every day at 12 am. So how can I provide life to users using AlarmManager.
Here is my code for MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.timeRemain);
long timeRemaining;
final TimePicker timePicker = findViewById(R.id.timepicker);
findViewById(R.id.alarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(),
timePicker.getMinute(),
0
);
}else {
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(),
timePicker.getCurrentMinute(),
0
);
}
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long timeInMillis) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, Alarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY,
pendingIntent);
Toast.makeText(this,"Alarm is Set", Toast.LENGTH_SHORT) .show();
}
}
My alarmReciever class
public class Alarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
Any Suggestions? Thanks in Advance.

I found the answer. we can use CountdownTimer to find the remaining time.
Here is the code:
long total = calendar.getTimeInMillis();
diff = total-System.currentTimeMillis();
countDownTimer = new CountDownTimer(diff, 1000) {
#Override
public void onTick(long millisUntilFinished) {
diff = millisUntilFinished;
int minutes = (int) (diff/1000) / 60;
int seconds = (int) (diff/1000) %60;
textView.setText("TIme Remain:" + minutes + ":" + seconds);
}
#Override
public void onFinish() {
textView.setText("00:00");
}
}.start();

Related

Alarm Manager using Broadcast receiver

I am creating an android app to set alarm using broadcast receiver. Its working fine when the app is open but when I closed the app completely then there is no notification generated. How to resolve this issue?
Broadcast Receiver class
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Alarm Fired");
MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
Toast.makeText(context,"ALarm fired",Toast.LENGTH_SHORT).show();
} }
Main Activity class
public class MainActivity extends AppCompatActivity {
//the timepicker object
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the timepicker object
timePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
//attaching clicklistener on button
findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//We need a calendar object to get the specified time in millis
//as the alarm manager method takes time in millis to setup the alarm
Calendar calendar = Calendar.getInstance();
if (android.os.Build.VERSION.SDK_INT >= 23) {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(), timePicker.getMinute(), 0);
} else {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
}
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long time) {
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyBroadcastReceiver.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
} }
AndroidManifest.xml
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true">
</receiver>

Alarm is not stopping

I am working on alarm with android and broadcast receiver. Setting up and playing an alarm works but I cannot turn off the alarm. I have two button for set alarm and stop alarm .My codes is here;
public class MainActivity extends AppCompatActivity {
Button btn;
private Button startAlarmBtn;
private TimePickerDialog timePickerDialog;
final static int REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cancel;
startAlarmBtn = (Button) findViewById(R.id.startAlarmBtn);
startAlarmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPickerDialog(false);
}
});
cancel=(Button)findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopAlarm();
}
});
}
private void openPickerDialog(boolean is24hour) {
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
MainActivity.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24hour);
timePickerDialog.setTitle("Alarm Ayarla");
timePickerDialog.show();
}
TimePickerDialog.OnTimeSetListener onTimeSetListener
= new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(calNow) <= 0){
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
}};
private void setAlarm(Calendar alarmCalender){
Toast.makeText(getApplicationContext(),"Alarm OK!",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalender.getTimeInMillis(), pendingIntent);
}
private void stopAlarm(){
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE,
new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pendingIntent.cancel();
}
}
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
How do I turn off the alarm?
My other question is, is it appropriate to have them in the main thread?
Should I use AsyncTask or multi-threading?
Thank you.
The alarm is not stopping because you don't have a handle to the ringtone instance you are playing.
I suggest you add a timer to auto stop the ringtone, or you create a global instance of the ringtone, which on second thought might be a bad idea, because if you forget to clean up, it may leak and cause other problems.
A simple approach to timing this is as shown below:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
new CountDownTimer(30000, 1000) { // a timer for 30 seconds, that updates approximately every second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// stop your ringtone here, or do other necessary stuff here
// you might want to check if the ringtone was not stopped before this method
}
}.start();
}
}
In response to your second question, you could as well use a thread with a handler or runnable to manage the ringtone accordingly. An AsyncTask may be too much work for something relatively simple.

how to use alarm manager for int increase

I want to increase a number and show it in a TextView using AlarmManager at a specific time of day, but it is not working.
App is debugging and showing 0, but not increasing the int number.
Please help, here is the code.
public class MainActivity extends AppCompatActivity {
TextView tv;
int a = 3;
Calendar calendar = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
MyAlarm alarm = new MyAlarm();
setAlarm(calendar.getTimeInMillis());
int g = alarm.i;
tv.setText(String.format("%d", g));
}
private void setAlarm(long time) {
calendar.setTimeInMillis(System.currentTimeMillis());
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 55);
calendar.set(Calendar.SECOND, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
broad cast is here,
public class MyAlarm extends BroadcastReceiver {
int i;
#Override
public void onReceive(Context context, Intent intent) {
i++;
}
}
To add a default constructor, try the following in your MyAlarm class:
MyAlarm(){
}
Also add this method:
public int setI(){
i = i+1;
return i;
}
This is what it should look like now:
public class MyAlarm extends BroadcastReceiver{
int i;
MyAlarm(){
i=0;
}
public int setI(){
i = i+1;
return i;
}
#Override
public void onReceive(Context context,Intent intent) {
i++;
}
}
Now, call this in onCreate() and it will increment i.
You can say
int g = myAlarm.setI();
in your setAlarm() function or wherever you want to increment it.
g will now be incremented. I hope this helps!

Dismiss alarm in android

The first time I worked on broadcast part and run this app, it worked (the alarm went off).
But second time I added cancelAlarm() part and ran it again. It didn't even go off. So I was guessing the previous alarm I had set wasn't removed so the app cant get new input(Alarm) by user.
However I'm not sure. I will really appreciate your feedback. Here's what I have right now.
public class MainActivity extends AppCompatActivity {
Calendar calendar = Calendar.getInstance();
TextView dp0;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dp0 = (TextView) findViewById(R.id.tv);
Button sButton = (Button)findViewById(R.id.btn);
sButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new TimePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Light_Dialog,onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
}
});
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(getApplicationContext(), "Set", Toast.LENGTH_SHORT).show();
setAlarm(calendar.getTimeInMillis());
dp0.setText(hourOfDay + ":" + minute);
final Button sButton1 = (Button) findViewById(R.id.cancelbtn);
sButton1.setVisibility(View.VISIBLE);
sButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dp0.setText("");
sButton1.setVisibility(View.INVISIBLE);
cancelAlarm();
}
});
}
};
public void setAlarm(long timeInMillis) {
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this,MyAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.set(AlarmManager.RTC_WAKEUP,timeInMillis,pendingIntent);
}
public void cancelAlarm() {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent("Myalarm");
PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.cancel(sender);
sender.cancel();
Toast.makeText(getApplicationContext(),"Canceled",Toast.LENGTH_SHORT).show();
}
}
And the BroadcastReceiver:
public class MyAlarm extends BroadcastReceiver {
MediaPlayer mediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
I think you need to use PendingIntent.FLAG_UPDATE_CURRENT. Moreover, I would like to recommend some changes in your code.
For setting the alarm change your function setAlarm() like this.
public void setAlarm(long timeInMillis) {
Intent myIntent = new Intent(getApplicationContext(), MyAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, timeInMillis, pendingIntent);
}
And for cancelling, the cancelAlarm() should look like.
public void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), MyAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
You might consider taking the onClickListener of sButton1 out of the function onTimeSet. Move the click listener to onCreate function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dp0 = (TextView) findViewById(R.id.tv);
Button sButton = (Button)findViewById(R.id.btn);
Button sButton1 = (Button)findViewById(R.id.cancelbtn);
sButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new TimePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Light_Dialog,onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
}
});
sButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dp0.setText("");
sButton1.setVisibility(View.INVISIBLE);
cancelAlarm();
}
});
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(getApplicationContext(), "Set", Toast.LENGTH_SHORT).show();
setAlarm(calendar.getTimeInMillis());
dp0.setText(hourOfDay + ":" + minute);
sButton1.setVisibility(View.VISIBLE);
}
};

Alarm clock doesnot work for the schedule time and day

I am working on alarm clock for my project in android and i am new to programming. I have got my alarm clock app working but it does not work for the schedule time so if I set the clock for Sunday 12 pm it does not work.
public class AlarmClock extends Activity {
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
AlarmManager alarmManager;
private EditText descriptionText;
private static MainActivity inst;
private CheckBox checkBox1,checkBox2,checkBox3,checkBox4,checkBox5,checkBox6,checkBox7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_clock);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
checkBox1= (CheckBox) findViewById(R.id.sundayCheckBox);
checkBox2= (CheckBox) findViewById(R.id.mondayCheckBox);
checkBox3= (CheckBox) findViewById(R.id.tuesdayCheckBox);
checkBox4= (CheckBox) findViewById(R.id.wednesdayCheckBox);
checkBox5= (CheckBox) findViewById(R.id.thursdayCheckBox);
checkBox6= (CheckBox) findViewById(R.id.fridayCheckBox);
checkBox7= (CheckBox) findViewById(R.id.saturdayCheckBox);
}
public void save (View v){
if (checkBox1.isChecked())
{
activityToPerform(1);
}
if (checkBox2.isChecked())
{
activityToPerform(2);
}
if (checkBox3.isChecked())
{
activityToPerform(3);
}
if (checkBox4.isChecked())
{
activityToPerform(4);
}
if (checkBox5.isChecked())
{
activityToPerform(5);
}
if (checkBox6.isChecked())
{
activityToPerform(6);
}
if (checkBox7.isChecked())
{
activityToPerform(7);
}
}
private void activityToPerform(int week)
{
Log.d("MainActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, week);
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
descriptionText= (EditText)findViewById(R.id.descriptionEditText);
Intent myIntent = new Intent(this, AlarmBroadcast.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
Starting API 19, the alarmManager.set() method is not delivered at precise time. See this : http://developer.android.com/reference/android/app/AlarmManager.html#set(int, long, android.app.PendingIntent)
You should use setExact() instead

Categories

Resources