Reputation: 1
I'm a beginner to android development.
I'm developing an app that need to play alarm exactly from 8 hrs from the time which am clicking a button.
I've created a line which gets the current time but am stuck to calculate 8 hrs from current time and play the alarm tone.
Here's my code:
import android.os.Bundle;
import android.app.Activity;
import android.widget.ToggleButton;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.view.*;
public class MainActivity extends Activity {
public ToggleButton tgb1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tgb1 = (ToggleButton) findViewById(R.id.toggleButton1);
tgb1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if (tgb1.getText().toString().equals("Click to Turn Off"))
{
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String strDate = sdf.format(c.getTime());
c.add(Calendar.HOUR,8);
But I don't know to proceed further from here. Kindly help me in calculating 8 hrs from current time and play alarm tone.
Waiting for your kind response.
Thanks.
Upvotes: 0
Views: 178
Reputation: 10661
You have to use AlarmManager to run your code at a later time. According to Android documentation
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
Since you already have the Calendar object c
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
where pendingIntent can have a service Class invoked which plays the audio tone.
Upvotes: 1
Reputation: 1
You can use AlarmManager.
And this can help you too. Always add (c.Add) minutes/hours/days to the Calendar instance before formatting and assigning value to String because now your "strDate" equals to the actual time without 8 hours added later.
Upvotes: 0