17 展訊Sprd設定-電池-監聽手指擡起事件判斷是否有觸控事件
阿新 • • 發佈:2018-11-23
1. 功能
通過監聽手指擡起的事件,記錄對應時間戳,通過最近2次手指擡起時間判斷是否有觸控事件
2. 監聽手指觸控事件
package com.android.server.power; import android.content.Context; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.util.Slog; import android.view.GestureDetector; import android.view.InputDevice; import android.view.MotionEvent; import android.view.WindowManagerPolicy.PointerEventListener; public class SystemTouchEventListener implements PointerEventListener { private static final String TAG = "PowerController.SysTouchEvt"; private final boolean DEBUG = isDebug(); private final boolean DEBUG_MORE = false; private final boolean TEST = PowerController.TEST; private final Context mContext; private final Callbacks mCallbacks; public SystemTouchEventListener(Context context, Callbacks callbacks) { mContext = context; mCallbacks = callbacks; } @Override public void onPointerEvent(MotionEvent event) { if (!event.isTouchEvent()) { return; } switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: //if (DEBUG) Slog.d(TAG, "Event " + event); if (mCallbacks != null) mCallbacks.onDown(); break; case MotionEvent.ACTION_POINTER_DOWN: break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_HOVER_MOVE: break; case MotionEvent.ACTION_UP: // 手指擡起 //if (DEBUG) Slog.d(TAG, "Event " + event); if (mCallbacks != null) mCallbacks.onUp(); break; case MotionEvent.ACTION_CANCEL: break; default: if (DEBUG) Slog.d(TAG, "Ignoring " + event); } } interface Callbacks { void onDown(); void onUp(); } private boolean isDebug(){ return Build.TYPE.equals("eng") || Build.TYPE.equals("userdebug"); } }
3. 記錄手指擡起時的時間戳
// system touch event listener private SystemTouchEventListener mSystemTouchEventListener; private WindowManagerFuncs mWindowManagerFuncs; private long mLastTouchEventTimeStamp = 0; // register system touch event listener private void registerTouchEventListener() { mSystemTouchEventListener = new SystemTouchEventListener(mContext, new SystemTouchEventListener.Callbacks() { @Override public void onDown() { } @Override public void onUp() { mLastTouchEventTimeStamp = SystemClock.elapsedRealtime(); if (DEBUG) Slog.d(TAG, "TouchEvent Up: mLastTouchEventTimeStamp:" + mLastTouchEventTimeStamp); } }); if (mWindowManagerFuncs != null) { mWindowManagerFuncs.registerPointerEventListener(mSystemTouchEventListener); } }
4. 判斷是否有使用者觸控行為
如果當前時間與上一次手指擡起的時間只差小於1秒,則使用者正在進行觸控行為。
當然也可以使用down事件進行判斷
private boolean isUserTouchActive() { long now = SystemClock.elapsedRealtime(); long lastTouchTime = 0; if (mPowerControllerInternal != null) lastTouchTime = mPowerControllerInternal.getLastTouchEventTimeStamp(); return ((now - lastTouchTime) <= 1000); }