简体   繁体   中英

Using a button to trigger alarm

So I want to use a button to lead over to a new activity that can pick between two ints(hours and mins) rather than setting an alarm. Or maybe do something different to access the value of those ints and change them? Is there a better way to code that?

My code so far is this - am I doing it right so far?

public class AlarmPtest extends Activity implements  android.view.View.OnClickListener{
/** Called when the activity is first created. */

Button SetAlarm, SetTimer;
int hours = 1, min = 30;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Vars();

}


private void AlarmClock() {
    // TODO Auto-generated method stub
    Intent i = new Intent(android.provider.AlarmClock.ACTION_SET_ALARM);
    i.putExtra(android.provider.AlarmClock.EXTRA_HOUR, hours);
    i.putExtra(android.provider.AlarmClock.EXTRA_MINUTES, min);
    startActivity(i);

}


private void Vars() {
    // TODO Auto-generated method stub
    SetAlarm = (Button) findViewById(R.id.SetAlarm);
    SetTimer = (Button) findViewById(R.id.TimerAlarm);

    SetAlarm.setOnClickListener(this);
    SetTimer.setOnClickListener(this);
}


public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()){
    case R.id.SetAlarm:
        Toast alarmToast = Toast.makeText(this, "you click alarm", Toast.LENGTH_LONG);
        alarmToast.show();
        AlarmClock();
     case R.id.TimerAlarm:
        Toast TimerToast = Toast.makeText(this, "you get 15 min", Toast.LENGTH_LONG);
        TimerToast.show();
        hours = 0 ;
        min = 15;
        AlarmClock();
    }
}

}

Your code is right, in the sense that your hours and mins will be pased in the alarm intent. And the alarm will be set if the user has Android SDK >= 9

BTW a common code convention in Java and thus Android, is to write function names starting with smallLetters. Hence, change your functions to:

private void alarmClock()
private void vars()

Otherwise, people might get the impression your referring to a Class. The same convention is used for variable names, so you will want to change your buttons as well:

Button setAlarm, setTimer;

You will probably want to use the TimePicker . This provides a nice interface to select time for an alarm. It occurs in an AlertDialog type interface so you won't need to launch a new Activity to select the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM