1. 程式人生 > >一種高效的android雙擊退出(可擴充套件多擊)

一種高效的android雙擊退出(可擴充套件多擊)

參考Google,安卓手機中在檢視安卓系統版本的地方,三擊或者多擊會出現彩蛋,可以借鑑其原始碼進行實現。

//利用陣列來儲存時間
    long[] mHits = new long[3];
    @Override
    public void onClick(View v) {
        // arraycopy 拷貝陣列
        /*  引數解讀如下:
         *  src the source array to copy the content.   拷貝哪個陣列
         *    srcPos the starting index of the content in src.  從原陣列中的哪裡開始拷貝
         *    dst the destination array to copy the data into.  拷貝到哪個陣列
         *    dstPos the starting index for the copied content in dst.  從目標陣列的那個位置開始去寫
         *    length the number of elements to be copied.  拷貝的長度
         */
//實現的功能就相當於把mHits從索引1開始的資料向前移動一位(0位資料被覆蓋),然後把當前距離時間寫入到陣列的最後一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //獲取離開機的時間
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        //單擊時間的間隔,以500毫秒為臨界值
        if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
            System.out.println("我被三擊了。。。");
            //一個三擊(雙擊或多擊事件完成),
            //把陣列置為空並重寫初始化,為下一次三擊(雙擊或多擊)做準備
            mHits = null;
            mHits = new long[3];
        }

上面,如果陣列長度改為2,那麼就是雙擊了