[英]How to close an HttpUrlConnection after 5 minutes without getting an exception in Java?
[英]how to close activity after x minutes?
我正在尋找最簡單的方法來關閉x分鍾后打開的活動。 android是否提供倒計時課程,還是我必須自己制作一個?
我已經嘗試過此代碼,但無法正常工作
Thread isOnDisplayThread = new Thread(new Runnable() {
@Override
public void run() {
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
Log.d(TAG, (isApplicationOnDisplay) ? "Application on display" : "APPLICATION ON BACKGROUND");
if (!isApplicationOnDisplay) {
notOnDisplayTime++;
if (notOnDisplayTime >= 10) {
Process.killProcess(Process.myPid());
}
} else {
notOnDisplayTime = 0;
}
}
}, 0, 1000);
}
});
isOnDisplayThread.run();
Handler handler = new Handler();
Runnable r=new Runnable() {
@Override
public void run() {
finish();
}
};
handler.postDelayed(r, 2000);
永遠也永遠不會*調用Java Thread
的run()
方法。 調用其start()
方法,這將導致Java 在新線程內為您調用其run()
方法。
它不起作用,因為您正在調用run方法。 它不會啟動線程。 因此,您需要調用start方法來調用線程
isOnDisplayThread.start();
另外,要結束線程,您需要調用
finish() ///method of the Activity class
如果代碼是在Activity類中包含的,則只需調用finish()方法
if (notOnDisplayTime >= 10) {
finish();
}
private final long startTime = 200000;
private final long interval = 1000;
countDownTimer = new MalibuCountDownTimer(startTime, interval);
countDownTimer.start();
public class MalibuCountDownTimer extends CountDownTimer{
public MalibuCountDownTimer(long startTime, long interval){
super(startTime, interval);
}
@Override
public void onFinish(){
txttimer.setText("Time's up!");
//timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
@Override
public void onTick(long millisUntilFinished) {
//text.setText("Time remain:" + millisUntilFinished);
//timeElapsed = startTime - millisUntilFinished;
String format = String.format("%%0%dd",2);
String seconds = String.format(format, millisUntilFinished/1000 % 60);
String minutes = String.format(format, (millisUntilFinished /(1000*60))%60);
String hours = String.format(format, (millisUntilFinished /(1000*60*60))%24);
String time = hours + ":" + minutes + ":" + seconds;
txttimer.setText("Time Remaining:" + time);
TimeUnit.MILLISECONDS.toMinutes(timeElapsed) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeElapsed)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
System.out.println(hms);
//text.setText("Time remain:" + h+":"+m+":"+s);
//timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
聲明Timer並調用finish()
。 一段時間后,它將關閉您的活動。
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.schedule(new TimerTask() {
@Override
public void run() {
finish();
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
只需使用Handler.postDelayed
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.