问题
I used alarm manager to do a work after a certain minute. But i need to find the remaining time whenever I open that activity.How to do that?
Intent myIntent = new Intent(Activity1.this, Activity2.class);
pendingIntent = PendingIntent.getService(Timeractivity.this, 0, myIntent, 0);
int time = Integer.parseInt(time_et.getText().toString());
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, time);
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
Toast.makeText(Timeractivity.this, "You set an timer of " + time + " minutes", Toast.LENGTH_LONG).show();
回答1:
This is not a good way to do a timer,
i would suggest using a CountDownTimer
then on onTick u get from that time u know the remaining time,
and best way in that case to move that data to the activity is using
intent.putExtra
read more here:
https://developer.android.com/reference/android/os/CountDownTimer.html
https://developer.android.com/reference/android/content/Intent.html
回答2:
java.util.Date EndTime; //time from you are calculating remaining
java.util.Date CurrentTime = null; // current time
SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm:ss");
CurrentTime = dateFormat2.parse(dateFormat2.format(new java.util.Date()));
EndTime = dateFormat2.parse(time_in_string);
long remaining_time = EndTime.getTime() - CurrentTime.getTime();//in milliseconds
回答3:
Try this:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Long NexClockTime = alarmManager.getNextAlarmClock().getTriggerTime();
Long now = System.currentTimeMillis();
Long timeLeft = NexClockTime - now;
回答4:
You have to create a timer and override its onTick method. Then you can update your timeleft variable in the intervals you want;
Check my complete answer here: https://stackoverflow.com/a/46012948/2351486
来源:https://stackoverflow.com/questions/42415007/how-to-get-remaining-time