How to pause and resume an Android Alarm? - android

I am developping an alarm, which vibrates in time defined intervals. So if I choose 5 seconds, the app will vibrates at each 5 seconds intervals. But I need to stop, pause, and resume the app.
This is my class:
public class AndroidAlarmService extends Activity {
private PendingIntent pendingIntent;
private Chronometer chronometer;
private Intent myIntent;
AlarmManager alarmManager;
Calendar calendar;
private long mTimeWhenStopped;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button) findViewById(R.id.startalarm);
Button buttonStop = (Button) findViewById(R.id.stopalarm);
Button buttonPause = (Button) findViewById(R.id.pausealarm);
Button buttonResume = (Button) findViewById(R.id.resumealarm);
chronometer = ((Chronometer) findViewById(R.id.clock_time));
myIntent = new Intent(AndroidAlarmService.this,
MyAlarmService.class);
pendingIntent = PendingIntent.getService(
AndroidAlarmService.this, 0, myIntent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar = Calendar.getInstance();
I start it in this method:
buttonStart.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
int initialValue = 0;
chronometer.setBase(SystemClock.elapsedRealtime() + initialValue);
chronometer.start();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 5 * 1000, pendingIntent);
Toast.makeText(AndroidAlarmService.this, "Start Alarm",
Toast.LENGTH_LONG).show();
}
});
This is used to pause:
buttonPause.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
stopRunning();
mTimeWhenStopped = chronometer.getBase() - SystemClock.elapsedRealtime();
// Tell the user about what we did.
Toast.makeText(AndroidAlarmService.this, "Resume!",
Toast.LENGTH_LONG).show();
}
});
I'd like to resume the app from the point it has started.
How can I do that?
Thank, you!

the following link might be helpful to you
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html

Related

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

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

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

I'm trying to create a daily countdown using AlarmManager in Android Studios

I'm trying to make something where a set number will decrease everyday, even if the app is closed, and not active. For instance, if you don't open the app for 5 days, when you do open it, the number will be 5 numbers lower. I've been trying to use AlarmManager, but I can only get it to make a Toast and not run a function in the main activity. Here is my code...
Main Activity
private TextView mTest;
private Button mButton;
private int number = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scheduleAlarm();
}
});
}
public void scheduleAlarm(){
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 100000, 100000, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT ));
Toast.makeText(MainActivity.this, "This is starting!", Toast.LENGTH_SHORT).show();
}
public void subtract(){
mTest = (TextView) findViewById(R.id.textView);
number -= 1;
String numberString = Integer.toString(number);
mTest.setText(numberString);
}
and Here is the broadcast
private MainActivity mMainActivity = new MainActivity();
#Override
public void onReceive(Context context, Intent intent) {
mMainActivity.subtract();
Toast.makeText(context, "This is bogus", Toast.LENGTH_LONG).show();
}
You can easily accomplish this using a Timer (https://developer.android.com/reference/java/util/Timer.html)
Follow this example:
long MINUTE_TO_MSEC = 60000;
long DAY_TO_MSEC = MINUTE_TO_MSEC * 60 * 24;
Timer timer = new Timer();
TimerTask countdownTask = new TimerTask() {
public void run() {
/* your function goes here */
}
}
timer.scheduleAtFixedRate(task,0,DAY_TO_MSEC);
This will run your code every 24 hours.

Android :: how can I restart service and run specific function at time x

PROBLEM
I want to know some concept to do like the topic said
what should be a requirement to do that
I think that PendingIntent and AlarmManager would be help to restart the service
at time x but I don't know that way to let it call function that I need
Please advice.
FOR EXAMPLE
I have 2 functions in my service class and I want to register it
to run one of these two (Depend on user propose) in the future at time x
SOME CODE THAT I WORK AROUND (EDIT)
public class MyActivity extends Activity implements View.OnClickListener {
private Button b1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button)findViewById(R.id.cmd1);
b1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
startIntentAt(5,MyReceiver.class);
finish();
}
private void startIntentAt(int seconds, Class<?> c) {
Intent myIntent = new Intent(getBaseContext(), c);
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, seconds);
//long interval = 60 * 1000; //
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, TargetActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
}

How to play alarm based on user enter value into edittext in Android

Hi want to play alarm in my app,so i tried using below code using services when i click start button alarm is playing..but what i want is,same activity i have two editexts in first i have give time 9,and second edittext i have given time 10,so i have to show notification only in 9 and 10 pm only...any one give me some idea.
public class DonnsAlarm extends Activity {
/** Called when the activity is first created. */
EditText e1,e2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s1));
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(DonnsAlarm.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(DonnsAlarm.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
PendingIntent pintent1 = PendingIntent.getService(DonnsAlarm.this, 1, intent,
0);
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s2));
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent1);
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
}
}
public class Service_class extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
notifyIntent.setClass(getApplicationContext(), DonnsAlarm.class);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from ="It's Time to Play VocCards!";
CharSequence message = "It's Time to Play VocCards!";
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
Notification notif = new Notification(R.drawable.ic_launcher,
"It's Time to Play VocCards!", System.currentTimeMillis());
notif.setLatestEventInfo(this, from, message, contentIntent);
nm.notify(1, notif);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
I see your problem is giving the values of EditTexts to service so service knows which hours to play the alarm. You can put the values of EditText to a bundle (or intent's extras) and start the service using that intent which contains data about the hours.
In your Activity use:
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
Intent intent = new Intent(getBaseContext(), Service_class.class);
intent.putExtra("value1", s1);
intent.putExtra("value2", s2);
startService(intent);
}
});
Than in your Service's onStartCommand method use this:
String val1 = intent.getExtra("value1");
String val2 = intent.getExtra("value2");
And now you have the values in your service!
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s1));
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(DonnsAlarm.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(DonnsAlarm.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
PendingIntent pintent1 = PendingIntent.getService(DonnsAlarm.this, 1, intent,
0);
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s2));
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent1);
}
});
The above code sets the two alarm one according to the value in 1st edittext and one according to the other

Categories

Resources