按powerkey唤醒启动上层Andord

参考


直接上流程图





一,基本代码分析

1. @InputManager.cpp (frameworks\native\services\inputflinger)
InputManager::InputManager(
        const sp<EventHubInterface>& eventHub,
        const sp<InputReaderPolicyInterface>& readerPolicy,
        const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
    mDispatcher = new InputDispatcher(dispatcherPolicy);
    mReader = new InputReader(eventHub, readerPolicy, mDispatcher);
    initialize();
}

void InputManager::initialize() { //初始化关于input输入和输出的线程
    mReaderThread = new InputReaderThread(mReader);
    mDispatcherThread = new InputDispatcherThread(mDispatcher);
}

status_t InputManager::start() {//启动关于input输入和输出的线程
    status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY); //线程优先级设置为了最高
    if (result) {
        ALOGE("Could not start InputDispatcher thread due to error %d.", result);
        return result;
    }

    result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);//线程优先级设置为了最高
    if (result) {
        ALOGE("Could not start InputReader thread due to error %d.", result);

        mDispatcherThread->requestExit();
        return result;
    }

    return OK;
}
2. @com_android_server_input_InputManagerService.cpp (frameworks\base\services\core\jni)
class NativeInputManager : public virtual RefBase,  //继承了InputReaderPolicyInterface和InputDispatcherPolicyInterface,所以输入输出事件的处理都是它
    public virtual InputReaderPolicyInterface,
    public virtual InputDispatcherPolicyInterface,
    public virtual PointerControllerPolicyInterface

NativeInputManager::NativeInputManager(jobject contextObj,
        jobject serviceObj, const sp<Looper>& looper) :
        mLooper(looper), mInteractive(true) {
    mInteractive = true;

    sp<EventHub> eventHub = new EventHub();
    mInputManager = new InputManager(eventHub, this, this);
}

static void nativeStart(JNIEnv* env, jclass /* clazz */, jlong ptr) {
    NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);

    status_t result = im->getInputManager()->start();//启动mInputManager中的两线程,开始读取来自kernel的输入事件,并且开始分发给android
    if (result) {
        jniThrowRuntimeException(env, "Input manager could not be started.");
    }
}

static struct {
...
    jmethodID interceptKeyBeforeQueueing;
} gServiceClassInfo;

int register_android_server_InputManager(JNIEnv* env) {
    int res = jniRegisterNativeMethods(env, "com/android/server/input/InputManagerService",
       				     gInputManagerMethods, NELEM(gInputManagerMethods)); //完成java标准的native函数的映射工作
 		...
    // Callbacks 设置回调函数
    jclass clazz;
    FIND_CLASS(clazz, "com/android/server/input/InputManagerService"); //找到InputManagerService类
    GET_METHOD_ID(gServiceClassInfo.interceptKeyBeforeQueueing, clazz,
            "interceptKeyBeforeQueueing", "(Landroid/view/KeyEvent;I)I"); //映射InputManagerService类的函数到gServiceClassInfo.interceptKeyBeforeQueueing,
}

void NativeInputManager::interceptKeyBeforeQueueing(const KeyEvent* keyEvent,
        uint32_t& policyFlags) {
    if ((policyFlags & POLICY_FLAG_TRUSTED)) {
        nsecs_t when = keyEvent->getEventTime();
        JNIEnv* env = jniEnv();
        jobject keyEventObj = android_view_KeyEvent_fromNative(env, keyEvent);
        jint wmActions;
        if (keyEventObj) {
            wmActions = env->CallIntMethod(mServiceObj,  //调用java的回调函数InputManagerService.java的interceptKeyBeforeQueueing
                    gServiceClassInfo.interceptKeyBeforeQueueing,
                    keyEventObj, policyFlags);
....
}
...
}
3. @InputManagerService.java (frameworks\base\services\core\java\com\android\server\input)
   // Native callback.
    private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
        return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags); //调用interceptKeyBeforeQueueing@InputMonitor.java 
    }

    public void start() {
        Slog.i(TAG, "Starting input manager");
        nativeStart(mPtr);//最终调用到nativeStart@com_android_server_input_InputManagerService.cpp
....
    }
4. @InputMonitor.java (frameworks\base\services\core\java\com\android\server\wm)
    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
        return mService.mPolicy.interceptKeyBeforeQueueing(event, policyFlags);
    }
5. @PhoneWindowManager.java (frameworks\base\services\core\java\com\android\server\policy)
  public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
final int keyCode = event.getKeyCode();

 switch (keyCode) {
            case KeyEvent.KEYCODE_POWER: {
                // Any activity on the power button stops the accessibility shortcut
                cancelPendingAccessibilityShortcutAction();
                result &= ~ACTION_PASS_TO_USER;
                isWakeKey = false; // wake-up will be handled separately
                if (down) {
                    interceptPowerKeyDown(event, interactive);
                } else {
                    interceptPowerKeyUp(event, interactive, canceled);
                }
                break;
            }
}
   }

    mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "PhoneWindowManager.mPowerKeyWakeLock");

    private void interceptPowerKeyDown(KeyEvent event, boolean interactive) {
....
if (!mPowerKeyHandled) {
            if (interactive) {
                // When interactive, we're already awake.
                // Wait for a long press or for the button to be released to decide what to do.
                if (hasLongPressOnPowerBehavior()) {
                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
                    msg.setAsynchronous(true);
                    mHandler.sendMessageDelayed(msg,
                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
                }
            } else {
                wakeUpFromPowerKey(event.getDownTime());

                if (mSupportLongPressPowerWhenNonInteractive && hasLongPressOnPowerBehavior()) {
                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
                    msg.setAsynchronous(true);
                    mHandler.sendMessageDelayed(msg,
                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
                    mBeganFromNonInteractive = true;
                } else {
                    final int maxCount = getMaxMultiPressPowerCount();

                    if (maxCount <= 1) {
                        mPowerKeyHandled = true;
                    } else {
                        mBeganFromNonInteractive = true;
                    }
                }
            }
        }
    }

    private void wakeUpFromPowerKey(long eventTime) {
//从这开始可以CPU boost,加快唤醒处理!!!
        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");//唤醒的原因:android.policy:POWER表示是按power键
    }

    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
        mActiveWakeup = true;
        final boolean theaterModeEnabled = isTheaterModeEnabled();
        if (!wakeInTheaterMode && theaterModeEnabled) {
            return false;
        }

        if (theaterModeEnabled) {
            Settings.Global.putInt(mContext.getContentResolver(),
                    Settings.Global.THEATER_MODE_ON, 0);
        }

        mPowerManager.wakeUp(wakeTime, reason); //通过binder调用到PowerManagerService.wakeUp
        return true;
    }
6. @PowerManager.java (frameworks\base\core\java\android\os)
7. @PowerManagerService.java (frameworks\base\services\core\java\com\android\server\power)
    public void wakeUp(long eventTime, String reason, String opPackageName) {
。。。
            final int uid = Binder.getCallingUid();
            final long ident = Binder.clearCallingIdentity();
            try {
                wakeUpInternal(eventTime, reason, uid, opPackageName, uid);
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
        }

    private void wakeUpInternal(long eventTime, String reason, int uid, String opPackageName,
            int opUid) {
        synchronized (mLock) {
            if (wakeUpNoUpdateLocked(eventTime, reason, uid, opPackageName, opUid)) {
                updatePowerStateLocked();
            }
        }
    }

    private boolean wakeUpNoUpdateLocked(long eventTime, String reason, int reasonUid,
            String opPackageName, int opUid) {
        if (DEBUG_SPEW) {
            Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
        }

        if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
                || !mBootCompleted || !mSystemReady) {
            return false;
        }

        Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);

        Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
        try {
            switch (mWakefulness) {
                case WAKEFULNESS_ASLEEP:
                    Slog.i(TAG, "Waking up from sleep (uid=" + reasonUid + " reason=" + reason
                            + ")...");
                    break;
                case WAKEFULNESS_DREAMING:
                    Slog.i(TAG, "Waking up from dream (uid=" + reasonUid + " reason=" + reason
                            + ")...");
                    break;
                case WAKEFULNESS_DOZING:
                    Slog.i(TAG, "Waking up from dozing (uid=" + reasonUid + " reason=" + reason
                            + ")...");
                    break;
            }

            mLastWakeTime = eventTime; //设置唤醒计时的开始时间
            setWakefulnessLocked(WAKEFULNESS_AWAKE, 0);

            mNotifier.onWakeUp(reason, reasonUid, opPackageName, opUid);
            userActivityNoUpdateLocked(
                    eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_POWER);
        }
        return true;
    }

    private void updatePowerStateLocked() {
        if (!mSystemReady || mDirty == 0) {
            return;
        }
        if (!Thread.holdsLock(mLock)) {
            Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
        }

        Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
        try {
            // Phase 0: Basic state updates.
            updateIsPoweredLocked(mDirty);
            updateStayOnLocked(mDirty);
            updateScreenBrightnessBoostLocked(mDirty);

            // Phase 1: Update wakefulness.
            // Loop because the wake lock and user activity computations are influenced
            // by changes in wakefulness.
            final long now = SystemClock.uptimeMillis();
            int dirtyPhase2 = 0;
            for (;;) {
                int dirtyPhase1 = mDirty;
                dirtyPhase2 |= dirtyPhase1;
                mDirty = 0;

                updateWakeLockSummaryLocked(dirtyPhase1);
                updateUserActivitySummaryLocked(now, dirtyPhase1);
                if (!updateWakefulnessLocked(dirtyPhase1)) {
                    break;
                }
            }

            // Phase 2: Update display power state.
            boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);

            // Phase 3: Update dream state (depends on display ready signal).
            updateDreamLocked(dirtyPhase2, displayBecameReady);

            // Phase 4: Send notifications, if needed.
            finishWakefulnessChangeIfNeededLocked();

            // Phase 5: Update suspend blocker.
            // Because we might release the last suspend blocker here, we need to make sure
            // we finished everything else first!
            updateSuspendBlockerLocked();
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_POWER);
        }
    }

    private void finishWakefulnessChangeIfNeededLocked() {
        if (mWakefulnessChanging && mDisplayReady) {
            if (mWakefulness == WAKEFULNESS_DOZING
                    && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
                return; // wait until dream has enabled dozing
            }
            if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
                logSleepTimeoutRecapturedLocked();
            }
            if (mWakefulness == WAKEFULNESS_AWAKE) {
                logScreenOn();
            }
            mWakefulnessChanging = false;
            mNotifier.onWakefulnessChangeFinished();//调用到Notifier.java
        }
    }

    private void logScreenOn() {
        Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);

        final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);

        LogMaker log = new LogMaker(MetricsEvent.SCREEN);
        log.setType(MetricsEvent.TYPE_OPEN);
        log.setSubtype(0); // not user initiated
        log.setLatency(latencyMs); // How long it took.
        MetricsLogger.action(log);
        EventLogTags.writePowerScreenState(1, 0, 0, 0, latencyMs);

        if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {//SCREEN_ON_LATENCY_WARNING_MS = 200毫秒
            Slog.w(TAG, "Screen on took " + latencyMs+ " ms");
        }
    }
8. @Notifier.java (frameworks\base\services\core\java\com\android\server\power)
    /**
     * Notifies that the device has finished changing wakefulness.
     */
    public void onWakefulnessChangeFinished() {
        if (DEBUG) {
            Slog.d(TAG, "onWakefulnessChangeFinished");
        }

        if (mInteractiveChanging) {
            mInteractiveChanging = false;
            handleLateInteractiveChange();
        }
    }

    private void handleLateInteractiveChange() {
        synchronized (mLock) {
            if (mInteractive) {
                // Finished waking up...
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mPolicy.finishedWakingUp(); //调用到PowerManagerService.finishedWakingUp
                    }
                });
            } else {
9. @PowerManagerService.java (frameworks\base\services\core\java\com\android\server\power)
    // Called on the PowerManager's Notifier thread.
    @Override
    public void finishedWakingUp() {
        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");

        if (mKeyguardDelegate != null) {
            mKeyguardDelegate.onFinishedWakingUp();
        }
    }
二,sensordevice的使能流程
1. @Sensors.cpp (vendor\mediatek\proprietary\hardware\sensor\sensors-1.0)
注册HAL module
struct sensors_module_t HAL_MODULE_INFO_SYM = {
    .common = {
        .tag = HARDWARE_MODULE_TAG,
        .version_major = 1,
        .version_minor = 0,
        .id = SENSORS_HARDWARE_MODULE_ID,  //#define SENSORS_HARDWARE_MODULE_ID "sensors" 
        .name = "MTK SENSORS Module",
        .author = "Mediatek",
        .methods = &sensors_module_methods,
    },
    .get_sensors_list = sensors__get_sensors_list,
};

static struct hw_module_methods_t sensors_module_methods = {
    .open = open_sensors
};

static int open_sensors(const struct hw_module_t* module, const char* name,
        struct hw_device_t** device)
{
   ALOGD("%s: name: %s!\r\n", __func__, name);
   return init_sensors(module, device);
}

static int poll__activate(struct sensors_poll_device_t * /* dev */,
        int handle, int enabled) {
    return mSensorManager->activate(mNativeConnection, handle - ID_OFFSET, enabled);
}

static int init_sensors(hw_module_t const* module, hw_device_t** device)
{
    sensors_poll_context_t *dev;

    dev = sensors_poll_context_t::getInstance();
    memset(&dev->device, 0, sizeof(sensors_poll_device_1));

    dev->device.common.tag      = HARDWARE_DEVICE_TAG;
    dev->device.common.version  = SENSORS_DEVICE_API_VERSION_1_3;
    dev->device.common.module   = const_cast<hw_module_t*>(module);
    dev->device.common.close    = poll__close;
    dev->device.activate        = poll__activate;
    dev->device.setDelay        = poll__setDelay;
    dev->device.poll            = poll__poll;
    dev->device.batch           = poll__batch;
    dev->device.flush           = poll__flush;

    *device = &dev->device.common;

    mSensorManager = SensorManager::getInstance();
    mNativeConnection = mSensorManager->createSensorConnection(numFds);
    mSensorManager->setNativeConnection(mNativeConnection);
    mSensorManager->setSensorContext(dev);//设置sensors_poll_context_t到SensorManager
    mVendorInterface = VendorInterface::getInstance();
    mMtkInterface = MtkInterface::getInstance();
    mSensorCalibration = SensorCalibration::getInstance();
    return 0;
}

2. @SensorContext.cpp (vendor\mediatek\proprietary\hardware\sensor\sensors-1.0)
sensors_poll_context_t::sensors_poll_context_t()
{
    mSensors[accel] = new AccelerationSensor();
    mPollFds[accel].fd = mSensors[accel]->getFd();
    mPollFds[accel].events = POLLIN;
    mPollFds[accel].revents = 0;

    mSensors[proximity] = new ProximitySensor(); //添加了Psensor
    mPollFds[proximity].fd = mSensors[proximity]->getFd();
    mPollFds[proximity].events = POLLIN;
    mPollFds[proximity].revents = 0;
     }

int sensors_poll_context_t::activate(int handle, int enabled) {
    int err = 0;
    int index = handleToDriver(handle);//通过handle找到对应的sensor index

    if ((index >= numFds) || (index < 0)) {
        ALOGE("activate error index = %d\n", index);
        return 0;
    }
    if (NULL != mSensors[index])
        err = mSensors[index]->enable(handle, enabled); //比如获取的是Psensor, 则调用到Proximity.cpp 
    return err;
}
3. @ Proximity.cpp(vendor\mediatek\proprietary\hardware\sensor\sensors-1.0 )//硬件抽象层的接口,直接操作VFS节点
int ProximitySensor::enable(int32_t handle, int en)
{
    int fd = -1;
    int flags = en ? 1 : 0;

    ALOGI("enable: handle:%d, en:%d \r\n",handle,en);
    strlcpy(&input_sysfs_path[input_sysfs_path_len], "psactive", sizeof(input_sysfs_path) - input_sysfs_path_len); ///"sys/class/sensor/m_ps_misc/psactive"
    fd = TEMP_FAILURE_RETRY(open(input_sysfs_path, O_RDWR));
    if (fd < 0) {
          ALOGE("no enable control attr\r\n" );
          return -1;
    }

    char buf[2]={0};
    buf[1] = 0;
    if (flags) {
         buf[0] = '1';
         mEnabledTime = getTimestamp() + IGNORE_EVENT_TIME;
         mPendingEvent.distance = -1; //reset p sensor value to invalid.
    } else {
         buf[0] = '0';
    }
    mEnabled = flags; //assign enable after reset p sensor value.
    TEMP_FAILURE_RETRY(write(fd, buf, sizeof(buf))); //如果是enable 则等同于命令 echo 1 > sys/class/sensor/m_ps_misc/psactive
    close(fd);
    return 0;
}
4. @SensorManager.cpp (vendor\mediatek\proprietary\hardware\sensor\sensors-1.0)
int SensorManager::activate(SensorConnection* connection, int32_t sensor_handle, bool enabled) {
...
    if (actuateHardware) {
        ALOGI_IF(DEBUG_CONNECTIONS, "\tactivate>>> actuating h/w activate handle=%d enabled=%d",
            sensor_handle, enabled);
        err = mSensorContext->activate(  //mSensorContext就是SensorContext.cpp
                sensor_handle,
                enabled);
        ALOGE_IF(err, "activate Error %s sensor %d", enabled ? "activating" : "disabling", sensor_handle);

        if (err != 0 && enabled) {
            // Failure when enabling the sensor. Clean up on failure.
            info.removeBatchParamsForIdent(connection);
        }
    }
}
5. SensorService.cpp (frameworks\native\services\sensorservice)
enable handle==8 和handle==1 的两个sensor?
status_t SensorService::enable(const sp<SensorEventConnection>& connection,
        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
        const String16& opPackageName) {
    sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    ...
    // Check maximum delay for the sensor.
    nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
    if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
        samplingPeriodNs = maxDelayNs;
    }
    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
    if (samplingPeriodNs < minDelayNs) {
        samplingPeriodNs = minDelayNs;
    }
    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
                                 maxBatchReportLatencyNs);

    // Call flush() before calling activate() on the sensor. Wait for a first
    // flush complete event before sending events on this connection. Ignore
    // one-shot sensors which don't support flush(). Ignore on-change sensors
    // to maintain the on-change logic (any on-change events except the initial
    // one should be trigger by a change in value). Also if this sensor isn't
    // already active, don't call flush().
    if (err == NO_ERROR &&
            sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
            rec->getNumConnections() > 1) {
        connection->setFirstFlushPending(handle, true);
        status_t err_flush = sensor->flush(connection.get(), handle);
        // Flush may return error if the underlying h/w sensor uses an older HAL.
        if (err_flush == NO_ERROR) {
            rec->addPendingFlushConnection(connection.get());
        } else {
            connection->setFirstFlushPending(handle, false);
        }
    }

    if (err == NO_ERROR) {
        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
        err = sensor->activate(connection.get(), true);
    }
}

sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
        int requestedMode, const String16& opPackageName) {
...
    uid_t uid = IPCThreadState::self()->getCallingUid();
    pid_t pid = IPCThreadState::self()->getCallingPid();

    String8 connPackageName =
            (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
    String16 connOpPackageName =
            (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
    sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName, //在此创建了一个SensorEventConnection
            requestedMode == DATA_INJECTION, connOpPackageName));
    if (requestedMode == DATA_INJECTION) {
        if (mActiveConnections.indexOf(result) < 0) {
            mActiveConnections.add(result);
        }
        // Add the associated file descriptor to the Looper for polling whenever there is data to
        // be injected.
        result->updateLooperRegistration(mLooper);
    }
    return result;
}
6. @SensorDevice.cpp (frameworks\native\services\sensorservice)
 
mSensors = ISensors::getService(); //???得到的是

status_t SensorDevice::batch(
        void* ident,
        int handle,
        int flags,
        int64_t samplingPeriodNs,
        int64_t maxBatchReportLatencyNs) {

    if (prevBestBatchParams != info.bestBatchParams) {
        ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
                 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
        err = StatusFromResult(
                checkReturn(mSensors->batch(
                    handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch)));
        if (err != NO_ERROR) {
            ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
                  mSensors.get(), handle, info.bestBatchParams.mTSample,
                  info.bestBatchParams.mTBatch, strerror(-err));
            info.removeBatchParamsForIdent(ident);
        }
    }

}

status_t SensorDevice::activate(void* ident, int handle, int enabled) {
    if (enabled) {
        ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));

        if (isClientDisabledLocked(ident)) {
            ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
                    ident, handle);
            return INVALID_OPERATION;
        }

        if (info.batchParams.indexOfKey(ident) >= 0) {
          if (info.numActiveClients() == 1) {  //亮屏后psensor 一般是第一次使用
              // This is the first connection, we need to activate the underlying h/w sensor.
              actuateHardware = true;
          }
        } else {
            // Log error. Every activate call should be preceded by a batch() call.
            ALOGE("\t >>>ERROR: activate called without batch");
        }
    } else {
...

    if (actuateHardware) {
        ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle, enabled);
        err = StatusFromResult(checkReturn(mSensors->activate(handle, enabled))); //mSensors = ISensors::getService();这个调用到哪里了???
        ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
                 strerror(-err));

        if (err != NO_ERROR && enabled) {
            // Failure when enabling the sensor. Clean up on failure.
            info.removeBatchParamsForIdent(ident);
        }
    }
}
7. @SensorEventConnection.cpp (frameworks\native\services\sensorservice)
class SensorService::SensorEventConnection:
    public BnSensorEventConnection, public LooperCallback  //继承自BnSensorEventConnection

status_t SensorService::SensorEventConnection::enableDisable(
        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
        int reservedFlags)
{
    status_t err;
    if (enabled) {
        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
                               reservedFlags, mOpPackageName); //调用的就是SensorService.cpp中的enable

    } else {
        err = mService->disable(this, handle);
    }
    return err;
}
8. @ISensorEventConnection.cpp (frameworks\native\libs\sensor)
status_t BnSensorEventConnection::onTransact( //binder服务端
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    switch(code) {
        case ENABLE_DISABLE: {
            CHECK_INTERFACE(ISensorEventConnection, data, reply);
            int handle = data.readInt32();
            int enabled = data.readInt32();
            nsecs_t samplingPeriodNs = data.readInt64();
            nsecs_t maxBatchReportLatencyNs = data.readInt64();
            int reservedFlags = data.readInt32();
            status_t result = enableDisable(handle, enabled, samplingPeriodNs,  //调用到了enableDisable@SensorEventConnection.cpp 
                                            maxBatchReportLatencyNs, reservedFlags);
            reply->writeInt32(result);
            return NO_ERROR;
        }

}
9. @SystemSensorManager.java (frameworks\base\core\java\android\hardware) ?????上次是从这开始调用
private static abstract class BaseEventQueue {
        private int enableSensor(
                Sensor sensor, int rateUs, int maxBatchReportLatencyUs) {
            if (nSensorEventQueue == 0) throw new NullPointerException();
            if (sensor == null) throw new NullPointerException();
            return nativeEnableSensor(nSensorEventQueue, sensor.getHandle(), rateUs,
                    maxBatchReportLatencyUs);
        }
 }
10. @android_hardware_SensorManager.cpp (frameworks\base\core\jni)
static jint nativeEnableSensor(JNIEnv *env, jclass clazz, jlong eventQ, jint handle, jint rate_us,
                               jint maxBatchReportLatency) {
    sp<Receiver> receiver(reinterpret_cast<Receiver *>(eventQ));
    return receiver->getSensorEventQueue()->enableSensor(handle, rate_us, maxBatchReportLatency, 0);
}
11. @SensorEventQueue.cpp (frameworks\native\libs\sensor)
SensorEventQueue::SensorEventQueue(const sp<ISensorEventConnection>& connection)
    : mSensorEventConnection(connection), mRecBuffer(NULL), mAvailable(0), mConsumed(0),
      mNumAcksToSend(0) {
    mRecBuffer = new ASensorEvent[MAX_RECEIVE_BUFFER_EVENT_COUNT];
}

status_t SensorEventQueue::enableSensor(int32_t handle, int32_t samplingPeriodUs,
                                        int64_t maxBatchReportLatencyUs, int reservedFlags) const {
   //mSensorEventConnection是BpSensorEventConnection,通过binder调用到BnSensorEventConnection,也就是SensorEventConnection.enableDisable
    return mSensorEventConnection->enableDisable(handle, true, us2ns(samplingPeriodUs),
                                                 us2ns(maxBatchReportLatencyUs), reservedFlags);  
}
13. @ISensorEventConnection.cpp (frameworks\native\libs\sensor)
class BpSensorEventConnection : public BpInterface<ISensorEventConnection>  //binder客户端
{
    virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs,
                                   nsecs_t maxBatchReportLatencyNs, int reservedFlags)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISensorEventConnection::getInterfaceDescriptor());
        data.writeInt32(handle);
        data.writeInt32(enabled);
        data.writeInt64(samplingPeriodNs);
        data.writeInt64(maxBatchReportLatencyNs);
        data.writeInt32(reservedFlags);
        remote()->transact(ENABLE_DISABLE, data, &reply);
        return reply.readInt32();
    }

}
三, 如何添加使能Proximity传感器?
1. @PowerManagerService.java (frameworks\base\services\core\java\com\android\server\power)
   /**
     * Updates the global power state based on dirty bits recorded in mDirty.
     *
     * This is the main function that performs power state transitions.
     * We centralize them here so that we can recompute the power state completely
     * each time something important changes, and ensure that we do it the same
     * way each time.  The point is to gather all of the transition logic here.
     */
    private void updatePowerStateLocked() { //再往上的分析,请看前面的步骤
Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
// Phase 2: Update display power state.
            boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
    }

    /**
     * Updates the display power state asynchronously.
     * When the update is finished, mDisplayReady will be set to true.  The display
     * controller posts a message to tell us when the actual display power state
     * has been updated so we come back here to double-check and finish up.
     *
     * This function recalculates the display power state each time.
     *
     * @return True if the display became ready.
     */
    private boolean updateDisplayPowerStateLocked(int dirty) {
            mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest, //mDisplayManagerInternal是DisplayManagerService.LocalService 
                    mRequestWaitForNegativeProximity);
}
2. @DisplayManagerService.java (frameworks\base\services\core\java\com\android\server\display)
 private final class LocalService extends DisplayManagerInternal {
        @Override
        public boolean requestPowerState(DisplayPowerRequest request,
                boolean waitForNegativeProximity) {
            return mDisplayPowerController.requestPowerState(request,  //调用到DisplayPowerController.java
                    waitForNegativeProximity);
        }

}
3. @DisplayPowerController.java (frameworks\base\services\core\java\com\android\server\display)
  public boolean requestPowerState(DisplayPowerRequest request,
            boolean waitForNegativeProximity) {
        synchronized (mLock) {
            boolean changed = false;

            if (waitForNegativeProximity
                    && !mPendingWaitForNegativeProximityLocked) {
                mPendingWaitForNegativeProximityLocked = true;
                changed = true;
            }

            if (mPendingRequestLocked == null) {
                mPendingRequestLocked = new DisplayPowerRequest(request);
                changed = true;
            } else if (!mPendingRequestLocked.equals(request)) {
                mPendingRequestLocked.copyFrom(request);
                changed = true;
            }

            if (changed && !mPendingRequestChangedLocked) {
                mPendingRequestChangedLocked = true;
                sendUpdatePowerStateLocked();
            }
            return mDisplayReadyLocked;
        }
    }

    private void sendUpdatePowerStateLocked() {
        if (!mPendingUpdatePowerStateLocked) {
            mPendingUpdatePowerStateLocked = true;
            Message msg = mHandler.obtainMessage(MSG_UPDATE_POWER_STATE); //mHandler就是DisplayControllerHandler 
            msg.setAsynchronous(true);
            mHandler.sendMessage(msg);
        }
    }

    private final class DisplayControllerHandler extends Handler {
        public DisplayControllerHandler(Looper looper) {
            super(looper, null, true /*async*/);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_POWER_STATE:
                    updatePowerState();
                    break;

                case MSG_PROXIMITY_SENSOR_DEBOUNCED:
                    debounceProximitySensor();
                    break;

                case MSG_SCREEN_ON_UNBLOCKED:
                    if (mPendingScreenOnUnblocker == msg.obj) {
                        unblockScreenOn();
                        updatePowerState();
                    }
                    break;
                case MSG_SCREEN_OFF_UNBLOCKED:
                    if (mPendingScreenOffUnblocker == msg.obj) {
                        unblockScreenOff();
                        updatePowerState();
                    }
                    break;
            }
        }
    }

   private void updatePowerState() {
        // Compute the basic display state using the policy.
        // We might override this below based on other factors.
        int state;
        int brightness = PowerManager.BRIGHTNESS_DEFAULT;
        boolean performScreenOffTransition = false;
        switch (mPowerRequest.policy) {
            case DisplayPowerRequest.POLICY_OFF:
                state = Display.STATE_OFF;
                performScreenOffTransition = true;
                break;
            case DisplayPowerRequest.POLICY_DOZE:
                if (mPowerRequest.dozeScreenState != Display.STATE_UNKNOWN) {
                    state = mPowerRequest.dozeScreenState;
                } else {
                    state = Display.STATE_DOZE;
                }
                if (!mAllowAutoBrightnessWhileDozingConfig) {
                    brightness = mPowerRequest.dozeScreenBrightness;
                }
                break;
            case DisplayPowerRequest.POLICY_VR:
                state = Display.STATE_VR;
                break;
            case DisplayPowerRequest.POLICY_DIM:
            case DisplayPowerRequest.POLICY_BRIGHT:
            default:
                state = Display.STATE_ON;
                break;
        }

        // Apply the proximity sensor.
        if (mProximitySensor != null) {
            if (mPowerRequest.useProximitySensor && state != Display.STATE_OFF) {
                setProximitySensorEnabled(true);
                if (!mScreenOffBecauseOfProximity
                        && mProximity == PROXIMITY_POSITIVE) {
                    mScreenOffBecauseOfProximity = true;
                    sendOnProximityPositiveWithWakelock();
                }
            } else if (mWaitingForNegativeProximity
                    && mScreenOffBecauseOfProximity
                    && mProximity == PROXIMITY_POSITIVE
                    && state != Display.STATE_OFF) {
                setProximitySensorEnabled(true);
            } else {
                setProximitySensorEnabled(false);
                mWaitingForNegativeProximity = false;
            }
            if (mScreenOffBecauseOfProximity
                    && mProximity != PROXIMITY_POSITIVE) {
                mScreenOffBecauseOfProximity = false;
                sendOnProximityNegativeWithWakelock();
            }
        } else {
            mWaitingForNegativeProximity = false;
        }
        if (mScreenOffBecauseOfProximity) {
            state = Display.STATE_OFF;
        }

animateScreenStateChange(state, performScreenOffTransition);
   }

    private void animateScreenStateChange(int target, boolean performScreenOffTransition) {
 if (target == Display.STATE_ON) {
            // Want screen on.  The contents of the screen may not yet
            // be visible if the color fade has not been dismissed because
            // its last frame of animation is solid black.
            if (!setScreenState(Display.STATE_ON)) {
                return; // screen on blocked
            }
...
        } else if (target == Display.STATE_VR) {
      }
    private boolean setScreenState(int state, boolean reportOnly) {
        final boolean isOff = (state == Display.STATE_OFF);
        if (mPowerState.getScreenState() != state) {

            // If we are trying to turn screen off, give policy a chance to do something before we
            // actually turn the screen off.
            if (isOff && !mScreenOffBecauseOfProximity) {
                if (mReportedScreenStateToPolicy == REPORTED_TO_POLICY_SCREEN_ON) {
                    setReportedScreenState(REPORTED_TO_POLICY_SCREEN_TURNING_OFF);
                    blockScreenOff();
                    mWindowManagerPolicy.screenTurningOff(mPendingScreenOffUnblocker);
                    unblockScreenOff();
                } else if (mPendingScreenOffUnblocker != null) {
                    // Abort doing the state change until screen off is unblocked.
                    return false;
                }
            }
...
        if (!isOff && mReportedScreenStateToPolicy == REPORTED_TO_POLICY_SCREEN_OFF) { //亮屏才进入
            setReportedScreenState(REPORTED_TO_POLICY_SCREEN_TURNING_ON);
            mWindowManagerPolicy.screenTurningOn(mPendingScreenOnUnblocker); //调用到PhoneWindowManager,其继承于WindowManagerPolicy
        }
    }
4.@PhoneWindowManager.java (frameworks\base\services\core\java\com\android\server\policy)
KeyguardServiceDelegate mKeyguardDelegate;
    public void init(Context context, IWindowManager windowManager,
            WindowManagerFuncs windowManagerFuncs) {
        mKeyguardDelegate = new KeyguardServiceDelegate(mContext,
                new StateCallback() {
                    @Override
                    public void onTrustedChanged() {
                        mWindowManagerFuncs.notifyKeyguardTrustedChanged();
                    }
                });
}

    public void systemBooted() {
        bindKeyguard();
        synchronized (mLock) {
            mSystemBooted = true;
            if (mSystemReady) {
                mKeyguardDelegate.onBootCompleted();
            }
        }
        startedWakingUp();
        screenTurningOn(null);
        screenTurnedOn();
    }

    public void screenTurningOn(final ScreenOnListener screenOnListener) {
        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");

        updateScreenOffSleepToken(false);
        synchronized (mLock) {
            mScreenOnEarly = true;
            mScreenOnFully = false;
            mKeyguardDrawComplete = false;
            mWindowManagerDrawComplete = false;
            mScreenOnListener = screenOnListener;

            if (mKeyguardDelegate != null) {
                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT,
                        getKeyguardDrawnTimeout());
                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);//调用到KeyguardServiceDelegate.java 
            } else {
                if (DEBUG_WAKEUP) Slog.d(TAG,
                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
                finishKeyguardDrawn();
            }
        }
    }
5.@KeyguardServiceDelegate.java (frameworks\base\services\core\java\com\android\server\policy\keyguard)
private final ServiceConnection mKeyguardConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (DEBUG) Log.v(TAG, "*** Keyguard connected (yay!)");
            mKeyguardService = new KeyguardServiceWrapper(mContext,  //KeyguardService的BP端
                    IKeyguardService.Stub.asInterface(service), mCallback);
            if (mKeyguardState.systemIsReady) {
                // If the system is ready, it means keyguard crashed and restarted.
                mKeyguardService.onSystemReady();
                if (mKeyguardState.screenState == SCREEN_STATE_ON
                        || mKeyguardState.screenState == SCREEN_STATE_TURNING_ON) {
                    mKeyguardService.onScreenTurningOn(
                            new KeyguardShowDelegate(mDrawnListenerWhenConnect));
                }
                mDrawnListenerWhenConnect = null;
            }
        }
    public void onScreenTurningOn(final DrawnListener drawnListener) {
        if (mKeyguardService != null) {
            if (DEBUG) Log.v(TAG, "onScreenTurnedOn(showListener = " + drawnListener + ")");
            mKeyguardService.onScreenTurningOn(new KeyguardShowDelegate(drawnListener)); //mKeyguardService是KeyguardServiceWrapper
        } else {
            // try again when we establish a connection
            Slog.w(TAG, "onScreenTurningOn(): no keyguard service!");
            // This shouldn't happen, but if it does, show the scrim immediately and
            // invoke the listener's callback after the service actually connects.
            mDrawnListenerWhenConnect = drawnListener;
        }
        mKeyguardState.screenState = SCREEN_STATE_TURNING_ON;
    }
6.@KeyguardServiceWrapper.java (frameworks\base\services\core\java\com\android\server\policy\keyguard)
  @Override
    public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
        try {
            mService.onScreenTurningOn(callback); //mService是KeyguardService的代理,通过binder调用到onScreenTurningOn@KeyguardService.java 
        } catch (RemoteException e) {
            Slog.w(TAG , "Remote Exception", e);
        }
    }
7.@KeyguardService.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\keyguard)
 private KeyguardLifecyclesDispatcher mKeyguardLifecyclesDispatcher;
    public void onCreate() {
        ((SystemUIApplication) getApplication()).startServicesIfNeeded();
        mKeyguardViewMediator =
                ((SystemUIApplication) getApplication()).getComponent(KeyguardViewMediator.class);
        mKeyguardLifecyclesDispatcher = new KeyguardLifecyclesDispatcher(
                Dependency.get(ScreenLifecycle.class),
                Dependency.get(WakefulnessLifecycle.class));

    }

    private final IKeyguardService.Stub mBinder = new IKeyguardService.Stub() {
        @Override // Binder interface
        public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
            Trace.beginSection("KeyguardService.mBinder#onScreenTurningOn");
            checkPermission();
            mKeyguardViewMediator.onScreenTurningOn(callback);
            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.SCREEN_TURNING_ON);//mKeyguardLifecyclesDispatcher是KeyguardLifecyclesDispatcher
            Trace.endSection();
        }

        @Override // Binder interface
        public void onScreenTurnedOn() {
            Trace.beginSection("KeyguardService.mBinder#onScreenTurnedOn");
            checkPermission();
            mKeyguardViewMediator.onScreenTurnedOn();
            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.SCREEN_TURNED_ON);
            Trace.endSection();
        }
   }
8/@KeyguardLifecyclesDispatcher.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\keyguard)
  private final ScreenLifecycle mScreenLifecycle;
    void dispatch(int what) {
        mHandler.obtainMessage(what).sendToTarget();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SCREEN_TURNING_ON:
                    mScreenLifecycle.dispatchScreenTurningOn(); //mScreenLifecycle是ScreenLifecycle.java
                    break;
                case SCREEN_TURNED_ON:
                    mScreenLifecycle.dispatchScreenTurnedOn();
                    break;
}
9.@ScreenLifecycle.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\keyguard)
 public void dispatchScreenTurningOn() {
        setScreenState(SCREEN_TURNING_ON);
        dispatch(Observer::onScreenTurningOn);//会调用mScreenObserver.dispatchScreenTurningOn, mScreenObserver是ScreenLifecycle.Observer
    }
10.@StatusBar.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\statusbar\phone)
@Override
    public void start() {
        mScreenLifecycle = Dependency.get(ScreenLifecycle.class); //和mKeyguardLifecyclesDispatcher@KeyguardService.java 关联起来了
        mScreenLifecycle.addObserver(mScreenObserver);
   }

    ScreenLifecycle.Observer mScreenObserver = new ScreenLifecycle.Observer() {
        @Override
        public void onScreenTurningOn() {
            mFalsingManager.onScreenTurningOn();//调用到FalsingManager.java 
            mNotificationPanel.onScreenTurningOn();

            maybePrepareWakeUpFromAod();

            if (mLaunchCameraOnScreenTurningOn) {
                mNotificationPanel.launchCamera(false, mLastCameraLaunchSource);
                mLaunchCameraOnScreenTurningOn = false;
            }
        }

        @Override
        public void onScreenTurnedOn() {
            mScrimController.wakeUpFromAod();
            mDozeScrimController.onScreenTurnedOn();
        }

        @Override
        public void onScreenTurnedOff() {
            mFalsingManager.onScreenOff();
            // If we pulse in from AOD, we turn the screen off first. However, updatingIsKeyguard
            // in that case destroys the HeadsUpManager state, so don't do it in that case.
            if (!isPulsing()) {
                updateIsKeyguard();
            }
        }
    };
11.@Dependency.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui)
@Override
    public void start() {
        mProviders.put(AsyncSensorManager.class, () ->
                new AsyncSensorManager(mContext.getSystemService(SensorManager.class)));
    }
12.@FalsingManager.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\classifier)
"debug.falsing_log"
   private FalsingManager(Context context) {
        mContext = context;
        mSensorManager = Dependency.get(AsyncSensorManager.class);
    }

    public void onScreenTurningOn() {
        if (FalsingLog.ENABLED) {
            FalsingLog.i("onScreenTurningOn", new StringBuilder()
                    .append("from=").append(mScreenOn ? 1 : 0)
                    .toString());
            clearPendingWtf();
        }
        mScreenOn = true;
        if (sessionEntrypoint()) {
            mDataCollector.onScreenTurningOn();
        }
    }

    private boolean sessionEntrypoint() {
        if (!mSessionActive && shouldSessionBeActive()) {
            onSessionStart();
            return true;
        }
        return false;
    }

    private void onSessionStart() {
        if (FalsingLog.ENABLED) {
            FalsingLog.i("onSessionStart", "classifierEnabled=" + isClassiferEnabled());
            clearPendingWtf();
        }
        mBouncerOn = false;
        mSessionActive = true;

        if (mHumanInteractionClassifier.isEnabled()) {//调用到HumanInteractionClassifier.java
            registerSensors(CLASSIFIER_SENSORS);
        }
        if (mDataCollector.isEnabledFull()) {
            registerSensors(COLLECTOR_SENSORS);
        }
    }

    private void registerSensors(int [] sensors) {
        for (int sensorType : sensors) {
            Sensor s = mSensorManager.getDefaultSensor(sensorType);
            if (s != null) {

                // This can be expensive, and doesn't need to happen on the main thread.
                mUiOffloadThread.submit(() -> {
                    mSensorManager.registerListener(this, s, SensorManager.SENSOR_DELAY_GAME);//mSensorManager是AsyncSensorManager.java
                });
            }
        }
    }

@HumanInteractionClassifier.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\classifier)
     public boolean isEnabled() {
        return mEnableClassifier;
    }

    private void updateConfiguration() {
        boolean defaultValue = mContext.getResources().getBoolean(
                R.bool.config_lockscreenAntiFalsingClassifierEnabled); //默认值为true

        mEnableClassifier = 0 != Settings.Global.getInt(
                mContext.getContentResolver(),
                HIC_ENABLE, defaultValue ? 1 : 0);
    }
13. @AsyncSensorManager.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\util)
AsyncSensorManager继承自SensorManager
    @Override
    protected boolean registerListenerImpl(SensorEventListener listener, Sensor sensor, int delayUs,
            Handler handler, int maxReportLatencyUs, int reservedFlags) {
        mHandler.post(() -> {
            if (!mInner.registerListener(listener, sensor, delayUs, maxReportLatencyUs, handler)) { // mInner就是SensorManager
                Log.e(TAG, "Registering " + listener + " for " + sensor + " failed.");
            }
        });
        return true;
    }
14. @SensorManager.java (frameworks\base\core\java\android\hardware)
  public boolean registerListener(SensorEventListener listener, Sensor sensor, int samplingPeriodUs,
            int maxReportLatencyUs, Handler handler) {
        int delayUs = getDelay(samplingPeriodUs);
        return registerListenerImpl(listener, sensor, delayUs, handler, maxReportLatencyUs, 0);
    }
15. @SystemSensorManager.java (frameworks\base\core\java\android\hardware)
  @Override
    protected boolean registerListenerImpl(SensorEventListener listener, Sensor sensor,
            int delayUs, Handler handler, int maxBatchReportLatencyUs, int reservedFlags) {
        if (listener == null || sensor == null) {
            Log.e(TAG, "sensor or listener is null");
            return false;
        }
        // Trigger Sensors should use the requestTriggerSensor call.
        if (sensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
            Log.e(TAG, "Trigger Sensors should use the requestTriggerSensor.");
            return false;
        }
        if (maxBatchReportLatencyUs < 0 || delayUs < 0) {
            Log.e(TAG, "maxBatchReportLatencyUs and delayUs should be non-negative");
            return false;
        }
        if (mSensorListeners.size() >= MAX_LISTENER_COUNT) {
            throw new IllegalStateException("register failed, " +
                "the sensor listeners size has exceeded the maximum limit " +
                MAX_LISTENER_COUNT);
        }

        // Invariants to preserve:
        // - one Looper per SensorEventListener
        // - one Looper per SensorEventQueue
        // We map SensorEventListener to a SensorEventQueue, which holds the looper
        synchronized (mSensorListeners) {
            SensorEventQueue queue = mSensorListeners.get(listener); //SensorEventQueue 继承于BaseEventQueue
            if (queue == null) {
                Looper looper = (handler != null) ? handler.getLooper() : mMainLooper;
                final String fullClassName = listener.getClass().getEnclosingClass() != null ?
                    listener.getClass().getEnclosingClass().getName() :
                    listener.getClass().getName();
                queue = new SensorEventQueue(listener, looper, this, fullClassName);
                if (!queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs)) {
                    queue.dispose();
                    return false;
                }
                mSensorListeners.put(listener, queue);
                return true;
            } else {
                return queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs);//queue是SensorEventQueue,继承于BaseEventQueue
            }
        }
    }

    private static abstract class BaseEventQueue {
        public boolean addSensor(
                Sensor sensor, int delayUs, int maxBatchReportLatencyUs) {
            // Check if already present.
            int handle = sensor.getHandle();
            if (mActiveSensors.get(handle)) return false;

            // Get ready to receive events before calling enable.
            mActiveSensors.put(handle, true);
            addSensorEvent(sensor);
            if (enableSensor(sensor, delayUs, maxBatchReportLatencyUs) != 0) {
                // Try continuous mode if batching fails.
                if (maxBatchReportLatencyUs == 0 ||
                    maxBatchReportLatencyUs > 0 && enableSensor(sensor, delayUs, 0) != 0) {
                  removeSensor(sensor, false);
                  return false;
                }
            }
            return true;
        }

        private int enableSensor(
                Sensor sensor, int rateUs, int maxBatchReportLatencyUs) {
            if (nSensorEventQueue == 0) throw new NullPointerException();
            if (sensor == null) throw new NullPointerException();
		Log.i(TAG, "peter_xu " + Log.getStackTraceString(new Throwable())); 
            return nativeEnableSensor(nSensorEventQueue, sensor.getHandle(), rateUs,
                    maxBatchReportLatencyUs);
        }
}

Psensor 驱动代码分析
@kernel-3.18/drivers/misc/mediatek/sensors-1.0/alsps/alsps.c 


修改方法:
1. @vendor/mediatek/proprietary/packages/apps/SystemUI/res/values/config.xml
<!-- If true, enable the advance anti-falsing classifier on the lockscreen. On some devices it
does not work well, particularly with noisy touchscreens. Note that disabling it may
increase the rate of unintentional unlocks. -->
<bool name="config_lockscreenAntiFalsingClassifierEnabled"> true </bool>
改为 false
则onSessionStart@FalsingManager.java (vendor\mediatek\proprietary\packages\apps\systemui\src\com\android\systemui\classifier)
将不会执行。

2. 测试方法
设置如下属性,则打开了FaslingManager.java的log输出
setprop debug.falsing_log true
setprop debug.falsing_logcat true
logcat -s FalsingLog






























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值