我正在Android Studio中开发应用程序。我如何设置计时器,然后在那时执行操作?
我正在获取系统日期和时间...并通过用户获取日期和时间。
然后我必须将两者进行比较并为此执行操作。
需要帮助这是我的代码:
================================================== =======================
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.TimePicker;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements
DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener{
TextView textView, textView2;
TextClock textClock;
TimePicker timePicker;
DatePicker datePicker;
Button button, button2;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String Date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textClock = (TextClock) findViewById(R.id.textClock);
// textClock.setFormat12Hour("hh:mm:ss aa");
// String time = textClock.getText().toString();
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
button = (Button) findViewById(R.id.button);
//Showing current time
calendar = Calendar.getInstance();
simpleDateFormat= new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date = simpleDateFormat.format(calendar.getTime());
textView.setText(Date);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, MainActivity.this, year, month, day);
datePickerDialog.show();
}
});
}
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
int yearFinal = i;
int monthFinal = i1+1;
int dayFinal = i2;
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog( MainActivity.this,
MainActivity.this, hour, minute);
timePickerDialog.show();
}
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
hourFinal = i;
minuteFinal = i1;
textView2.setText(earFinal + monthFinal + dayFinal + hourFinal + minuteFinal);
}
}
最佳答案
您可以计算当前日期和用户选择的日期之间的时差(以毫秒为单位)。
private long getTimeDelay(Calendar userPickedTime){
return userPickedTime.getTimeInMillis() - Calendar.getInstance().getTimeInMillis(); // Time difference
}
然后,您可以安排一个计时器在那时执行操作。
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// this code will be executed after time difference between current and user picked time.
}
}, getTimeDelay(userPickedTime));