1. 程式人生 > >Android關於介面一定時間無操作自動跳轉到指定介面的實現

Android關於介面一定時間無操作自動跳轉到指定介面的實現

最近在做一個售貨機的專案,當介面停留一定時間無操作需要自動跳轉到主頁播放宣傳廣告。下面把我實現的方式貼出來,經測試完美地實現所需功能。

主要用到的功能,自定義一個定時器CountTimer繼承CountDownTimer。

public class CountTimer extends CountDownTimer {
    private Context context;
/**
     * 引數 millisInFuture       倒計時總時間(如60S,120s等)
     * 引數 countDownInterval    漸變時間(每次倒計1s)
     */
public 
CountTimer(long millisInFuture, long countDownInterval,Context context) { super(millisInFuture, countDownInterval); this.context=context; } // 計時完畢時觸發 @Override public void onFinish() { UIHelper.showMainActivity((Activity) context); } // 計時過程顯示 @Override public void onTick
(long millisUntilFinished) { } }
方法很簡單,只需要在onFinish()方法中執行計時完畢的操作。

接下來在需要在執行的類裡呼叫該方法。

這裡我封裝了一個類。

public class BaseDispatchTouchActivity extends AppCompatActivity{
    private CountTimer countTimerView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
init(); } private void timeStart(){ new Handler(getMainLooper()).post(new Runnable() { @Override public void run() { countTimerView.start(); } }); } private void init() { //初始化CountTimer,設定倒計時為2分鐘。 countTimerView=new CountTimer(120000,1000,BaseDispatchTouchActivity.this); } /** * 主要的方法,重寫dispatchTouchEvent * @param ev * @return */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()){ //獲取觸控動作,如果ACTION_UP,計時開始。 case MotionEvent.ACTION_UP: countTimerView.start(); break; //否則其他動作計時取消 default:countTimerView.cancel(); break; } return super.dispatchTouchEvent(ev); } @Override protected void onPause() { super.onPause(); countTimerView.cancel(); } @Override protected void onResume() { super.onResume(); timeStart(); } }

到此主要實現方法已經完成,最後只需要在實現的activity繼承該類就行了。