工作学习 -- 总结内容供搜索

012. 模拟按键 input命令 
我测试发现,有两种方法可行。
①、Java.lang.Runtime

    Runtime runtime = Runtime.getRuntime();
    runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);

②、Android.app.Instrumentation

    Instrumentation inst = new Instrumentation();
    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);

都测试成功了。可以实现 按BACK 的效果。
Instrumentation是测试环境模拟用的,不能在生产环境中使用;Instrumentation不能在主线程中用,再开个线程就可以了

3. 调用系统计算器 android(适用于不同品牌) 
    /**打开计算机*/  
    public void openJS(){  
        PackageInfo pak = getAllApps(ChangeActivity.this, "Calculator","calculator"); //大小写  
        if(pak != null){  
           Intent intent = new Intent();    
              intent = this.getPackageManager().getLaunchIntentForPackage(pak.packageName);    
              startActivity(intent);  
              }else{  
               Toast.makeText(this, "未找到计算器", Toast.LENGTH_SHORT).show();  
              }    
    }  
      
    public  PackageInfo getAllApps(Context context,String app_flag_1,String app_flag_2) {  
        PackageManager pManager = context.getPackageManager();  
        // 获取手机内所有应用  
        List<PackageInfo> packlist = pManager.getInstalledPackages(0);  
        for (int i = 0; i < packlist.size(); i++) {  
            PackageInfo pak = (PackageInfo) packlist.get(i);  
             if(pak.packageName.contains(app_flag_1)||pak.packageName.contains(app_flag_2)){  
                 return pak;  
             }  
        }  
        return null;  
    }  

4. sensor框架
	blog.csdn.net/mr_raptor/article/details/8074549

5. Activity的四种launchMode 
	blog.csdn.net/liuhe688/article/details/6754323/

7. hardware/rockchip/sensor/st/ 总结:
	sensors.c 中定义八种传感器类型sensor_t 和 hal库入口HAL_MODULE_INFO_SYM(open_sensors->init_nusensors)
	nusensors.cpp 中初始化类型为sensors_poll_context_t的对象和操作函数(close、activate、setDelay、poll,对应着poll__close、poll__activate、poll__setDelay、poll__poll,
													其实际还是调用对象的delete、activate、setDelay、pollEvents);
		并管理和调用这八种传感器的接口(enable、setDelay、readEvents)
	enum {	具体操作reg由各个传感器对象来完成。	
		light           = 0, ID_L LightSensor()
		proximity       = 1, ID_P ProximitySensor()
		mma             = 2, ID_A MmaSensor()
		akm             = 3, ID_M ID_O AkmSensor()
		gyro            = 4, ID_GY GyroSensor()
		pressure        = 5, ID_PR PressureSensor()
		temperature	= 6, ID_TMP TemperatureSensor()
		numSensorDrivers,
		numFds,
    	};			
	struct i2c_device_id {
		char name[I2C_NAME_SIZE];
		kernel_ulong_t driver_data;	/* Data private to the driver */
	};

8. 测试
Index: device/rockchip/rk3288/BoardConfig.mk
===================================================================
--- device/rockchip/rk3288/BoardConfig.mk	(版本 422)
+++ device/rockchip/rk3288/BoardConfig.mk	(工作副本)
@@ -38,9 +38,9 @@
 MALLOC_IMPL := dlmalloc
 
 # Sensors
-BOARD_SENSOR_ST := false
-BOARD_SENSOR_MPU := true
-BOARD_USES_GENERIC_INVENSENSE := false
+BOARD_SENSOR_ST := true
+#BOARD_SENSOR_MPU := true
+#BOARD_USES_GENERIC_INVENSENSE := false
 
 # ------------ #
 # radical_update

<4>[    0.962862] sensor_register_slave:mma8452,id=17  kernel/drivers/input/sensors/accel/mma8452.c
<4>[    0.962877] sensor_register_slave:gs_mc3230,id=23 kernel/drivers/input/sensors/accel/mc3230.c
<4>[    0.962887] gsensor_init
<4>[    0.962897] sensor_register_slave:mpu6880_acc,id=24 kernel/drivers/input/sensors/accel/mpu6880_acc.c
<4>[    0.962908] sensor_register_slave:cm3217,id=48 kernel/drivers/input/sensors/lsensor/cm3217.c
<4>[    0.962919] sensor_register_slave:cm3218,id=49 kernel/drivers/input/sensors/lsensor/cm3218.c
<4>[    0.962928] gs_adxl345
<4>[    0.962937] sensor_register_slave:adxl345,id=25 kernel/drivers/input/sensors/gsensor/adxl345.c

SENSORS_HARDWARE_MODULE_ID

/dev/block/platform/ff0f0000.rksdmmc/by-name/boot

am start -n "com.android.calculator2/.Calculator"

device/rockchip/rk3288/BoardConfig.mk

adb connect 192.168.1.100
adb install ~/fu/mytest/apk/SensorTest\ \(2\).apk 
am start -n "com.routon.zoujm.accelsensortest/.MainActivity"


maybe,here:
	adb push ~/fu/jingshang/jingshang_3rd_5.1/out/target/product/rk3288/system/lib/hw/sensors.rk30board.so /system/lib/hw
	adb push ~/fu/jingshang/jingshang_3rd_5.1/out/target/product/rk3288/system/lib/libinvensense_hal.so /system/lib/


9. Sensor Usage
	SensorManager   sensorManager=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
	Sensor   accSensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	sensorManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_NORMAL);
	sensorManager.unregisterListener(this,accSensor);
	//然后在当前Activity中实现以下的两个函数
	public  void  onSensorChanged(SensorEventevent)
	public  void  onAccuracyChanged(Sensorsensor,intaccuracy)
1. 系统设置的图标路径 frameworks/base/core/res/res/drawable-mdpi/ic_settings_alpha.png
    ps:frameworks/base/core/res/res/drawable/ic_lock_settings.xml
2. 加载设置
	frameworks/base/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
	frameworks/base/policy/src/com/android/internal/policy/impl/GlobalActions.java
3. 设置的具体实现
	frameworks/base/services/core/java/com/android/server/power/PowerManagerService.java  updateSettingsLocked()
	frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
	frameworks/base/packages/SystemUI/src/com/android/systemui/settings/*
public final class SystemServer {
    // TODO: remove all of these references by improving dependency resolution and boot phases
    private PowerManagerService mPowerManagerService;
    private ActivityManagerService mActivityManagerService;
    private DisplayManagerService mDisplayManagerService;
    private PackageManagerService mPackageManagerService;
    private PackageManager mPackageManager;
    private ContentResolver mContentResolver;
	
    private boolean mOnlyCore;//由SystemProperties.get("vold.decrypt")决定,与Package Manager、Window Manager、MountService、DisplayManagerService相关
    private boolean mFirstBoot;//与Package Manager和Window Manager相关

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }
   1. 获取ro.factorytest的值:
	private final int mFactoryTestMode = SystemProperties.getInt("ro.factorytest", FACTORY_TEST_OFF);
   2. 执行run():
	1> 获取系统时间,并修正。
		if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
		    Slog.w(TAG, "System clock is before 1970; setting to 1970.");
		    SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
		}
	2> 设置VM库
		SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
	3> 使能采样仪the sampling profile
		        if (SamplingProfilerIntegration.isEnabled()) {
			    SamplingProfilerIntegration.start();
			    mProfilerSnapshotTimer = new Timer();
			    mProfilerSnapshotTimer.schedule(new TimerTask() {
				@Override
				public void run() {
				    SamplingProfilerIntegration.writeSnapshot("system_server", null);
				}
			    }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
			}
	4> 设置VMRuntime
        	VMRuntime.getRuntime().clearGrowthLimit();
		VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
	5> 设置ro.build.fingerprint
		由getString("ro.product.brand") + '/' + 
                    getString("ro.product.name") + '/' +
                    getString("ro.product.device") + ':' +
                    getString("ro.build.version.release") + '/' +
                    getString("ro.build.id") + '/' +
                    getString("ro.build.version.incremental") + ':' +
                    getString("ro.build.type") + '/' +
                    getString("ro.build.tags");组成
	6> 启动消息主线程,并在主线程中创建消息队列Prepare the main looper thread (this thread).
		android.os.Process.setThreadPriority(
		        android.os.Process.THREAD_PRIORITY_FOREGROUND);
		android.os.Process.setCanSelfBackground(false);
		Looper.prepareMainLooper();
	7> 加载android_servers库 
		// Initialize native services.
		System.loadLibrary("android_servers");
	8> Native层systemserver初始化
		property_get("system_init.startsensorservice", propBuf, "1");
		if (strcmp(propBuf, "1") == 0) {
			// Start the sensor service
			SensorService::instantiate();
		}
		class SensorService : 
			public BinderService<SensorService>,
			public BnSensorServer,
			protected Thread
		template<typename SERVICE>
		class BinderService	
		    static status_t publish(bool allowIsolated = false) {
			sp<IServiceManager> sm(defaultServiceManager());
			return sm->addService(
				String16(SERVICE::getServiceName()),
				new SERVICE(), allowIsolated);
		    }	
		    static void instantiate() { publish(); }

	9> 创建system service manager并注册在LocalServices中
		private SystemServiceManager mSystemServiceManager = new SystemServiceManager(mSystemContext);
		    private void createSystemContext() {
			ActivityThread activityThread = ActivityThread.systemMain();
			private Context mSystemContext = activityThread.getSystemContext();
			mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
		    }
			public class SystemServiceManager {
				public SystemServiceManager(Context context) {
					private final Context mContext = context;
				}
		LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
			public final class LocalServices {
			    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
		    		new ArrayMap<Class<?>, Object>();
			    /**
			     * Adds a service instance of the specified interface to the global registry of local services.
			     */
			    public static <T> void addService(Class<T> type, T service) {
				synchronized (sLocalServiceObjects) {
				    if (sLocalServiceObjects.containsKey(type)) {
					throw new IllegalStateException("Overriding service registration");
				    }
				    sLocalServiceObjects.put(type, service);
				}
			    }
	10> 启动各种服务,然后进入消息循环。
	        // Start services.
		try {
		    startBootstrapServices(); --a
		    startCoreServices(); --b
		    startOtherServices(); --c
		} catch (Throwable ex) {
		    Slog.e("System", "******************************************");
		    Slog.e("System", "************ Failure starting system services", ex);
		    throw ex;
		}

		// For debug builds, log event loop stalls to dropbox for analysis.
		if (StrictMode.conditionallyEnableDebugLogging()) {
		    Slog.i(TAG, "Enabled StrictMode for system server main thread.");
		}

		// Loop forever.
		Looper.loop();
		throw new RuntimeException("Main thread loop unexpectedly exited");
	11> 主要服务有	a Installer ActivityManagerService.Lifecycle ActivityManagerService PowerManagerService DisplayManagerService PackageManagerService UserManagerService
		 	b LightsService BatteryService UsageStatsService WebViewUpdateService
			c SchedulingPolicyService TelecomLoaderService TelephonyRegistry EntropyMixer AccountManagerService SimStateChangeService
			  ContentService VibratorService ConsumerIrService AlarmManagerService InputManagerService WindowManagerService BluetoothManagerService
			  InputMethodManagerService AccessibilityManagerService MountService LockSettingsService PersistentDataBlockService DevicePolicyManagerService.Lifecycle
			  StatusBarManagerService ClipboardService NetworkManagementService TextServicesManagerService NetworkScoreService NetworkStatsService NetworkPolicyManagerService
			  WifiP2pService WifiService PppoeService RttService WifiScanningService EthernetService ConnectivityService NsdService
    public static WindowManagerService main(final Context context,
            final InputManagerService im,
            final boolean haveInputMethods, final boolean showBootMsgs,
            final boolean onlyCore) {
        final WindowManagerService[] holder = new WindowManagerService[1];
        DisplayThread.getHandler().runWithScissors(new Runnable() {
            @Override
            public void run() {
                holder[0] = new WindowManagerService(context, im,
                        haveInputMethods, showBootMsgs, onlyCore);
            }
        }, 0);
        return holder[0];
    }
    private WindowManagerService(Context context, InputManagerService inputManager,
            boolean haveInputMethods, boolean showBootMsgs, boolean onlyCore) {
        mContext = context;
        mHaveInputMethods = haveInputMethods;
        mAllowBootMessages = showBootMsgs;
        mOnlyCore = onlyCore;
        mLimitedAlphaCompositing = context.getResources().getBoolean(
                com.android.internal.R.bool.config_sf_limitedAlpha);
        mHasPermanentDpad = context.getResources().getBoolean(
                com.android.internal.R.bool.config_hasPermanentDpad);
        mInTouchMode = context.getResources().getBoolean(
                com.android.internal.R.bool.config_defaultInTouchMode);
        mInputManager = inputManager; // Must be before createDisplayContentLocked.
        mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
        mDisplaySettings = new DisplaySettings();
        mDisplaySettings.readSettingsLocked();

        LocalServices.addService(WindowManagerPolicy.class, mPolicy);

        mPointerEventDispatcher = new PointerEventDispatcher(mInputManager.monitorInput(TAG));

        mFxSession = new SurfaceSession();
        mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = mDisplayManager.getDisplays();
        for (Display display : displays) {
            createDisplayContentLocked(display);
        }

        mKeyguardDisableHandler = new KeyguardDisableHandler(mContext, mPolicy);

        mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
        mPowerManagerInternal.registerLowPowerModeObserver(
                new PowerManagerInternal.LowPowerModeListener() {
            @Override
            public void onLowPowerModeChanged(boolean enabled) {
                synchronized (mWindowMap) {
                    if (mAnimationsDisabled != enabled) {
                        mAnimationsDisabled = enabled;
                        dispatchNewAnimatorScaleLocked(null);
                    }
                }
            }
        });
        mAnimationsDisabled = mPowerManagerInternal.getLowPowerModeEnabled();
        mScreenFrozenLock = mPowerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, "SCREEN_FROZEN");
        mScreenFrozenLock.setReferenceCounted(false);

        mAppTransition = new AppTransition(context, mH);

        mActivityManager = ActivityManagerNative.getDefault();
        mBatteryStats = BatteryStatsService.getService();
        mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
        AppOpsManager.OnOpChangedInternalListener opListener =
                new AppOpsManager.OnOpChangedInternalListener() {
                    @Override public void onOpChanged(int op, String packageName) {
                        updateAppOpsState();
                    }
                };
        mAppOps.startWatchingMode(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, null, opListener);
        mAppOps.startWatchingMode(AppOpsManager.OP_TOAST_WINDOW, null, opListener);

        // Get persisted window scale setting
        mWindowAnimationScaleSetting = Settings.Global.getFloat(context.getContentResolver(),
                Settings.Global.WINDOW_ANIMATION_SCALE, mWindowAnimationScaleSetting);
        mTransitionAnimationScaleSetting = Settings.Global.getFloat(context.getContentResolver(),
                Settings.Global.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScaleSetting);
        setAnimatorDurationScale(Settings.Global.getFloat(context.getContentResolver(),
                Settings.Global.ANIMATOR_DURATION_SCALE, mAnimatorDurationScaleSetting));

        // Track changes to DevicePolicyManager state so we can enable/disable keyguard.
        IntentFilter filter = new IntentFilter();
        filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
        mContext.registerReceiver(mBroadcastReceiver, filter);

        mSettingsObserver = new SettingsObserver();
        updateShowImeWithHardKeyboard();

        mHoldingScreenWakeLock = mPowerManager.newWakeLock(
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
        mHoldingScreenWakeLock.setReferenceCounted(false);

        mAnimator = new WindowAnimator(this);

        mAllowTheaterModeWakeFromLayout = context.getResources().getBoolean(
                com.android.internal.R.bool.config_allowTheaterModeWakeFromWindowLayout);

        mRotateOnBoot = isWindowFakeRotation();
        mIsTabletEnv = isTabletEnv();

        LocalServices.addService(WindowManagerInternal.class, new LocalService());
        initPolicy();

        // Add ourself to the Watchdog monitors.
        Watchdog.getInstance().addMonitor(this);

        SurfaceControl.openTransaction();
        try {
            createWatermarkInTransaction();
            mFocusedStackFrame = new FocusedStackFrame(
                    getDefaultDisplayContentLocked().getDisplay(), mFxSession);
        } finally {
            SurfaceControl.closeTransaction();
        }

        updateCircularDisplayMaskIfNeeded();
        showEmulatorDisplayOverlayIfNeeded();
	        //$_rbox_$_modify_$_chenxiao_begin,add for remotecontrol
        if (SystemProperties.getBoolean("ro.config.enable.remotecontrol",false)) {
            RCManager = new RemoteControlManager(context, this);
            RCManager.startListener();
        } else {
            RCManager = null;
        }
        //$_rbox_$_modify_$_begin
    }
class SensorService :
        public BinderService<SensorService>,
        public BnSensorServer,
        protected Thread

template<typename SERVICE>
class BinderService
{
public:
    static status_t publish(bool allowIsolated = false) {
        sp<IServiceManager> sm(defaultServiceManager());
        return sm->addService(
                String16(SERVICE::getServiceName()),
                new SERVICE(), allowIsolated);
    }

    static void publishAndJoinThreadPool(bool allowIsolated = false) {
        publish(allowIsolated);
        joinThreadPool();
    }

    static void instantiate() { publish(); }

    static status_t shutdown() { return NO_ERROR; }

private:
    static void joinThreadPool() {
        sp<ProcessState> ps(ProcessState::self());
        ps->startThreadPool();
        ps->giveThreadPoolName();
        IPCThreadState::self()->joinThreadPool();
    }
};

1. SensorService服务启动frameworks/native/services/sensorservice/main_sensorservice.cpp
	int main(int /*argc*/, char** /*argv*/) {
	    SensorService::publishAndJoinThreadPool();
	    return 0;
	}

2. SensorService继承了模板类BinderService<SensorService> 类型名SERVICE=SensorService
	SensorService::publishAndJoinThreadPool()会调用模板类BinderService的同名方法
	即先new SensorService(),然后注册到ServiceManager中,最后调用BinderService的私有方法joinThreadPool()方法:sensor服务加入线程池,等待客户端的请求。

3. 先看默认构造函数SensorService::SensorService()初始化几个字段:是否初始化check,socket的buffer大小,wakelock获取为false
    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
      mWakeLockAcquired(false){}

4. 最后按照系统服务的流程:生成sensor服务的实例对象,注册到系统中,创建线程池,在线程池中等待服务用户(客户端:服务的使用者)请求。

5. BnSensorServer是sensor服务的Stub
/**
 * A looper callback.
 */
class LooperCallback : public virtual RefBase {
protected:
    virtual ~LooperCallback() { }

public:
    /**
     * Handles a poll event for the given file descriptor.
     * It is given the file descriptor it is associated with,
     * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
     * and the data pointer that was originally supplied.
     *
     * Implementations should return 1 to continue receiving callbacks, or 0
     * to have this file descriptor and callback unregistered from the looper.
     */
    virtual int handleEvent(int fd, int events, void* data) = 0;
};

class RefBase
{
public:
            void            incStrong(const void* id) const;
            void            decStrong(const void* id) const;
    
            void            forceIncStrong(const void* id) const;

            //! DEBUGGING ONLY: Get current strong ref count.
            int32_t         getStrongCount() const;

    class weakref_type
    {
    public:
        RefBase*            refBase() const;
        
        void                incWeak(const void* id);
        void                decWeak(const void* id);
        
        // acquires a strong reference if there is already one.
        bool                attemptIncStrong(const void* id);
        
        // acquires a weak reference if there is already one.
        // This is not always safe. see ProcessState.cpp and BpBinder.cpp
        // for proper use.
        bool                attemptIncWeak(const void* id);

        //! DEBUGGING ONLY: Get current weak ref count.
        int32_t             getWeakCount() const;

        //! DEBUGGING ONLY: Print references held on object.
        void                printRefs() const;

        //! DEBUGGING ONLY: Enable tracking for this object.
        // enable -- enable/disable tracking
        // retain -- when tracking is enable, if true, then we save a stack trace
        //           for each reference and dereference; when retain == false, we
        //           match up references and dereferences and keep only the 
        //           outstanding ones.
        
        void                trackMe(bool enable, bool retain);
    };
    
            weakref_type*   createWeak(const void* id) const;
            
            weakref_type*   getWeakRefs() const;

            //! DEBUGGING ONLY: Print references held on object.
    inline  void            printRefs() const { getWeakRefs()->printRefs(); }

            //! DEBUGGING ONLY: Enable tracking of object.
    inline  void            trackMe(bool enable, bool retain)
    { 
        getWeakRefs()->trackMe(enable, retain); 
    }

    typedef RefBase basetype;

protected:
    RefBase();
    virtual  ~RefBase();
    
    //! Flags for extendObjectLifetime()
    enum {
        OBJECT_LIFETIME_STRONG  = 0x0000,
        OBJECT_LIFETIME_WEAK    = 0x0001,
        OBJECT_LIFETIME_MASK    = 0x0001
    };
    
    void  extendObjectLifetime(int32_t mode);
            
    //! Flags for onIncStrongAttempted()
    enum {
        FIRST_INC_STRONG = 0x0001
    };
    
    virtual void            onFirstRef();
    virtual void            onLastStrongRef(const void* id);
    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
    virtual void            onLastWeakRef(const void* id);

private:
    friend class weakref_type;
    class weakref_impl;
    
                            RefBase(const RefBase& o);
            RefBase&        operator=(const RefBase& o);

private:
    friend class ReferenceMover;

    static void renameRefs(size_t n, const ReferenceRenamer& renamer);

    static void renameRefId(weakref_type* ref,
            const void* old_id, const void* new_id);

    static void renameRefId(RefBase* ref,
            const void* old_id, const void* new_id);

        weakref_impl* const mRefs;
};
这里以surfaceflinger为例子:

1、在init中启动采用如下方式:
    int main(int argc, char** argv) {  
        SurfaceFlinger::publishAndJoinThreadPool(true);  
        // When SF is launched in its own process, limit the number of  
        // binder threads to 4.  
        ProcessState::self()->setThreadPoolMaxThreadCount(4);  
        return 0;  
    }  
总结出:xxxservice只需要Public BinderService即可,写个main函数就能启动服务,其中服务的注册由基类BinderService的publishAndJoinThreadPool来完成。
    static void publishAndJoinThreadPool(bool allowIsolated = false) {  
        sp<IServiceManager> sm(defaultServiceManager());  
        sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);//“SurfaceFlinger” 注册到SM中 
	ProcessState::self()->startThreadPool();  
        IPCThreadState::self()->joinThreadPool();//binder的交互    
    }  

以此方式启动的xxxservice只需在init.rc设置service xxxservice 可执行文件的path

2、在systemserver中添加相关的服务,比如systemserver的在init1中,或者init2.
    SurfaceFlinger::instantiate();//调用binderservice的publish函数  

    static status_t publish(bool allowIsolated = false) {  
        sp<IServiceManager> sm(defaultServiceManager());  
        return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);  
    }
frameworks$ find -name "*MediaPlayer*"
./av/include/media/IMediaPlayer.h
./av/include/media/IMediaPlayerService.h
./av/include/media/MediaPlayerInterface.h
./av/include/media/IMediaPlayerClient.h
./av/media/libmediaplayerservice/MediaPlayerService.cpp
./av/media/libmediaplayerservice/MediaPlayerFactory.cpp
./av/media/libmediaplayerservice/MediaPlayerFactory.h
./av/media/libmediaplayerservice/MediaPlayerService.h
./av/media/libmedia/IMediaPlayer.cpp
./av/media/libmedia/IMediaPlayerClient.cpp
./av/media/libmedia/IMediaPlayerService.cpp
./wilhelm/src/autogen/MPH_to_MediaPlayer.h
./wilhelm/src/objects/CMediaPlayer.c
./wilhelm/src/android/android_GenericMediaPlayer.h
./wilhelm/src/android/MediaPlayer_to_android.h
./wilhelm/src/android/MediaPlayer_to_android.cpp
./wilhelm/src/android/android_GenericMediaPlayer.cpp
./ex/variablespeed/src/com/android/ex/variablespeed/MediaPlayerDataSource.java
./ex/variablespeed/src/com/android/ex/variablespeed/MediaPlayerProxy.java
./ex/variablespeed/src/com/android/ex/variablespeed/SingleThreadedMediaPlayerProxy.java
./base/docs/html/sdk/api_diff/17/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/19/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/19/changes/android.media.MediaPlayer.TrackInfo.html
./base/docs/html/sdk/api_diff/9/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/21/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/21/changes/android.media.MediaPlayer.TrackInfo.html
./base/docs/html/sdk/api_diff/5/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/5/changes/android.widget.MediaController.MediaPlayerControl.html
./base/docs/html/sdk/api_diff/14/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/16/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/18/changes/android.widget.MediaController.MediaPlayerControl.html
./base/docs/html/sdk/api_diff/3/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/preview-21/changes/android.media.MediaPlayer.html
./base/docs/html/sdk/api_diff/preview-21/changes/android.media.MediaPlayer.TrackInfo.html
./base/docs/html/reference/com/google/android/gms/cast/RemoteMediaPlayer.OnMetadataUpdatedListener.html
./base/docs/html/reference/com/google/android/gms/cast/RemoteMediaPlayer.OnStatusUpdatedListener.html
./base/docs/html/reference/com/google/android/gms/cast/RemoteMediaPlayer.html
./base/docs/html/reference/com/google/android/gms/cast/RemoteMediaPlayer.MediaChannelResult.html
./base/media/jni/android_media_MediaPlayer.cpp
./base/media/java/android/media/MediaPlayer.java

frameworks$ find . -name media -type d
./av/include/private/media
./av/include/media
./av/media
./support/v4/kitkat/android/support/v4/media
./support/v4/jellybean-mr2/android/support/v4/media
./support/v4/api22/android/support/v4/media
./support/v4/api21/android/support/v4/media
./support/v4/ics/android/support/v4/media
./support/v4/java/android/support/v4/media
./support/v4/froyo/android/support/v4/media
./support/v4/jellybean/android/support/v4/media
./support/v4/jellybean-mr1/android/support/v4/media
./support/v7/mediarouter/jellybean-mr2/android/support/v7/media
./support/v7/mediarouter/src/android/support/v7/media
./support/v7/mediarouter/jellybean/android/support/v7/media
./support/v7/mediarouter/jellybean-mr1/android/support/v7/media
./native/include/media
./base/cmds/media
./base/cmds/media/src/com/android/commands/media
./base/packages/SimpleSystemUI/src/com/android/systemui/media
./base/packages/SystemUI/src/com/android/systemui/media
./base/docs/html/design/media
./base/docs/html/guide/topics/media
./base/tests/RemoteDisplayProvider/src/com/android/media
./base/tests/Camera2Tests/SmartCamera/SimpleCamera/tests/src/androidx/media
./base/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media
./base/services/core/java/com/android/server/media
./base/media
./base/media/mca/samples/CameraEffectsRecordingSample/java/android/media
./base/media/mca/effect/java/android/media
./base/media/lib/remotedisplay/java/com/android/media
./base/media/java/android/service/media
./base/media/java/android/media
1. wildcard : 扩展通配符  notdir : 去除路径  patsubst :替换通配符
	在Makefile规则中,通配符会被自动展开。但在变量的定义和函数引用时,通配符将失效。
	这种情况下如果需要通配符有效,就需要使用函数“wildcard”,它的用法是:$(wildcard PATTERN...) 。
	在Makefile中,它被展开为已经存在的、使用空格分开的、匹配此模式的所有文件列表。
	如果不存在任何符合此模式的文件,函数会忽略模式字符并返回空。
	需要注意的是:这种情况下规则中通配符的展开和上一小节匹配通配符的区别。
	一般我们可以使用“$(wildcard *.c)”来获取工作目录下的所有的.c文件列表。
	复杂一些用法:可以使用“$(patsubst %.c,%.o,$(wildcard *.c))”,
		首先使用“wildcard”函数获取工作目录下的.c文件列表;
		之后将列表中所有文件名的后缀.c替换为.o。这样我们就可以得到在当前目录可生成的.o文件列表。
		因此在一个目录下可以使用如下内容的Makefile来将工作目录下的所有的.c文件进行编译并最后连接成为一个可执行文件:
			#sample Makefile
				objects := $(patsubst %.c,%.o,$(wildcard *.c))
				foo : $(objects)
					cc -o foo $(objects)
				system/core/healthd analysis
1. batteryservice/BatteryService.h (frameworks/native/include/batteryservice/BatteryService.h)
	namespace android {

	// must be kept in sync with definitions in BatteryManager.java
	enum {
	    BATTERY_STATUS_UNKNOWN = 1, // equals BatteryManager.BATTERY_STATUS_UNKNOWN constant
	    BATTERY_STATUS_CHARGING = 2, // equals BatteryManager.BATTERY_STATUS_CHARGING constant
	    BATTERY_STATUS_DISCHARGING = 3, // equals BatteryManager.BATTERY_STATUS_DISCHARGING constant
	    BATTERY_STATUS_NOT_CHARGING = 4, // equals BatteryManager.BATTERY_STATUS_NOT_CHARGING constant
	    BATTERY_STATUS_FULL = 5, // equals BatteryManager.BATTERY_STATUS_FULL constant
	};

	// must be kept in sync with definitions in BatteryManager.java
	enum {
	    BATTERY_HEALTH_UNKNOWN = 1, // equals BatteryManager.BATTERY_HEALTH_UNKNOWN constant
	    BATTERY_HEALTH_GOOD = 2, // equals BatteryManager.BATTERY_HEALTH_GOOD constant
	    BATTERY_HEALTH_OVERHEAT = 3, // equals BatteryManager.BATTERY_HEALTH_OVERHEAT constant
	    BATTERY_HEALTH_DEAD = 4, // equals BatteryManager.BATTERY_HEALTH_DEAD constant
	    BATTERY_HEALTH_OVER_VOLTAGE = 5, // equals BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE constant
	    BATTERY_HEALTH_UNSPECIFIED_FAILURE = 6, // equals BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE constant
	    BATTERY_HEALTH_COLD = 7, // equals BatteryManager.BATTERY_HEALTH_COLD constant
	};

	// must be kept in sync with definitions in BatteryProperty.java
	enum {
	    BATTERY_PROP_CHARGE_COUNTER = 1, // equals BatteryProperty.CHARGE_COUNTER constant
	    BATTERY_PROP_CURRENT_NOW = 2, // equals BatteryProperty.CURRENT_NOW constant
	    BATTERY_PROP_CURRENT_AVG = 3, // equals BatteryProperty.CURRENT_AVG constant
	    BATTERY_PROP_CAPACITY = 4, // equals BatteryProperty.CAPACITY constant
	    BATTERY_PROP_ENERGY_COUNTER = 5, // equals BatteryProperty.ENERGY_COUNTER constant
	};

	struct BatteryProperties {
	    bool chargerAcOnline;
	    bool chargerUsbOnline;
	    bool chargerWirelessOnline;
	    int maxChargingCurrent;
	    int maxChargingVoltage;
	    int batteryStatus;
	    int batteryHealth;
	    bool batteryPresent;
	    int batteryLevel;
	    int batteryVoltage;
	    int batteryTemperature;
	    int batteryCurrent;
	    int batteryCycleCount;
	    int batteryFullCharge;
	    int batteryChargeCounter;
	    String8 batteryTechnology;

	    status_t writeToParcel(Parcel* parcel) const;
	    status_t readFromParcel(Parcel* parcel);
	};

	struct BatteryProperty {
	    int64_t valueInt64;

	    status_t writeToParcel(Parcel* parcel) const;
	    status_t readFromParcel(Parcel* parcel);
	};

	}; // namespace android

2. healthd/healthd.h
	struct healthd_config {
	    int periodic_chores_interval_fast;
	    int periodic_chores_interval_slow;

	    android::String8 batteryStatusPath;
	    android::String8 batteryHealthPath;
	    android::String8 batteryPresentPath;
	    android::String8 batteryCapacityPath;
	    android::String8 batteryVoltagePath;
	    android::String8 batteryTemperaturePath;
	    android::String8 batteryTechnologyPath;
	    android::String8 batteryCurrentNowPath;
	    android::String8 batteryCurrentAvgPath;
	    android::String8 batteryChargeCounterPath;
	    android::String8 batteryFullChargePath;
	    android::String8 batteryCycleCountPath;

	    int (*energyCounter)(int64_t *);
	    int boot_min_cap;
	    bool (*screen_on)(android::BatteryProperties *props);
	};

	enum EventWakeup {
	    EVENT_NO_WAKEUP_FD,
	    EVENT_WAKEUP_FD,
	};

	// Global helper functions

	int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup = EVENT_NO_WAKEUP_FD);
	void healthd_battery_update();
	android::status_t healthd_get_property(int id,
	    struct android::BatteryProperty *val);
	void healthd_dump_battery_state(int fd);

	struct healthd_mode_ops {
	    void (*init)(struct healthd_config *config);
	    int (*preparetowait)(void);
	    void (*heartbeat)(void);
	    void (*battery_update)(struct android::BatteryProperties *props);
	};

	extern struct healthd_mode_ops *healthd_mode_ops;

	// Charger mode  ===> implements in system/core/healthd/healthd_mode_charger.cpp

	void healthd_mode_charger_init(struct healthd_config *config);
	int healthd_mode_charger_preparetowait(void);
	void healthd_mode_charger_heartbeat(void);
	void healthd_mode_charger_battery_update(
	    struct android::BatteryProperties *props);

	// ===> implements in system/core/healthd/healthd_board_default.cpp , it is null actually.
	// The following are implemented in libhealthd_board to handle board-specific
	// behavior.
	//
	// healthd_board_init() is called at startup time to modify healthd's
	// configuration according to board-specific requirements.  config
	// points to the healthd configuration values described above.  To use default
	// values, this function can simply return without modifying the fields of the
	// config parameter.

	void healthd_board_init(struct healthd_config *config);

	// Process updated battery property values.  This function is called when
	// the kernel sends updated battery status via a uevent from the power_supply
	// subsystem, or when updated values are polled by healthd, as for periodic
	// poll of battery state.
	//
	// props are the battery properties read from the kernel.  These values may
	// be modified in this call, prior to sending the modified values to the
	// Android runtime.
	//
	// Return 0 to indicate the usual kernel log battery status heartbeat message
	// is to be logged, or non-zero to prevent logging this information.

	int healthd_board_battery_update(struct android::BatteryProperties *props);

	#endif /* _HEALTHD_H_ */

3. healthd/BatteryMonitor.h
	namespace android {

	class BatteryMonitor {
	  public:

	    enum PowerSupplyType {
		ANDROID_POWER_SUPPLY_TYPE_UNKNOWN = 0,
		ANDROID_POWER_SUPPLY_TYPE_AC,
		ANDROID_POWER_SUPPLY_TYPE_USB,
		ANDROID_POWER_SUPPLY_TYPE_WIRELESS,
		ANDROID_POWER_SUPPLY_TYPE_BATTERY
	    };

	    BatteryMonitor();
	    void init(struct healthd_config *hc);
	    bool update(void);
	    int getChargeStatus();
	    status_t getProperty(int id, struct BatteryProperty *val);
	    void dumpState(int fd);

	  private:
	    struct healthd_config *mHealthdConfig;
	    Vector<String8> mChargerNames;
	    bool mBatteryDevicePresent;
	    bool mAlwaysPluggedDevice;
	    int mBatteryFixedCapacity;
	    int mBatteryFixedTemperature;
	    struct BatteryProperties props;

	    int getBatteryStatus(const char* status);
	    int getBatteryHealth(const char* status);
	    int readFromFile(const String8& path, char* buf, size_t size);
	    PowerSupplyType readPowerSupplyType(const String8& path);
	    bool getBooleanField(const String8& path);
	    int getIntField(const String8& path);
	};

	}; // namespace android

4. 分析入口======> system/core/healthd/healthd.cpp :: main()
	struct healthd_mode_ops *healthd_mode_ops;
	默认	healthd_mode_ops = &android_ops;
				-------> implements in system/core/healthd/healthd_mode_android.cpp
		static struct healthd_mode_ops android_ops = {
		    .init = healthd_mode_android_init,
		    .preparetowait = healthd_mode_android_preparetowait,
		    .heartbeat = healthd_mode_nop_heartbeat, ==> static void healthd_mode_nop_heartbeat(void) {}
		    .battery_update = healthd_mode_android_battery_update,
		};
	分支
	charger: healthd_mode_ops = &charger_ops;
	c:	healthd_mode_ops = &charger_ops;
	r:	healthd_mode_ops = &recovery_ops;
	?:	exit(1);
				-------> implements in system/core/healthd/healthd_mode_charger.cpp
		static struct healthd_mode_ops charger_ops = {
		    .init = healthd_mode_charger_init,
		    .preparetowait = healthd_mode_charger_preparetowait,
		    .heartbeat = healthd_mode_charger_heartbeat,
		    .battery_update = healthd_mode_charger_battery_update,
		};
				-------> implements in here. it is null implemention.
		static struct healthd_mode_ops recovery_ops = {
		    .init = healthd_mode_nop_init,
		    .preparetowait = healthd_mode_nop_preparetowait,
		    .heartbeat = healthd_mode_nop_heartbeat,
		    .battery_update = healthd_mode_nop_battery_update,
		};
	healthd_init(); // 初始化
		static int healthd_init() {
		    epollfd = epoll_create(MAX_EPOLL_EVENTS); // 创建epoll线程池,用于存放客户端请求数据 // 参考IO多路复用之epoll
		    if (epollfd == -1) {
			KLOG_ERROR(LOG_TAG,
				   "epoll_create failed; errno=%d\n",
				   errno);
			return -1;
		    }

		    healthd_board_init(&healthd_config);
			static struct healthd_config healthd_config = {
			    .periodic_chores_interval_fast = DEFAULT_PERIODIC_CHORES_INTERVAL_FAST,
			    .periodic_chores_interval_slow = DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW,
			    .batteryStatusPath = String8(String8::kEmptyString),
			    .batteryHealthPath = String8(String8::kEmptyString),
			    .batteryPresentPath = String8(String8::kEmptyString),
			    .batteryCapacityPath = String8(String8::kEmptyString),
			    .batteryVoltagePath = String8(String8::kEmptyString),
			    .batteryTemperaturePath = String8(String8::kEmptyString),
			    .batteryTechnologyPath = String8(String8::kEmptyString),
			    .batteryCurrentNowPath = String8(String8::kEmptyString),
			    .batteryCurrentAvgPath = String8(String8::kEmptyString),
			    .batteryChargeCounterPath = String8(String8::kEmptyString),
			    .batteryFullChargePath = String8(String8::kEmptyString),
			    .batteryCycleCountPath = String8(String8::kEmptyString),
			    .energyCounter = NULL,
			    .boot_min_cap = 0,
			    .screen_on = NULL,
			};
		    healthd_mode_ops->init(&healthd_config);
		    wakealarm_init();
		    uevent_init();
		    gBatteryMonitor = new BatteryMonitor();
		    gBatteryMonitor->init(&healthd_config);
		    return 0;
		}
	healthd_mainloop(); // 进入loop,等待接受客户端请求
		static void healthd_mainloop(void) {
		    int nevents = 0;
		    while (1) {
			struct epoll_event events[eventct]; // healthd_register_event()-> eventct++;
			int timeout = awake_poll_interval;
			int mode_timeout;

			/* Don't wait for first timer timeout to run periodic chores */
			if (!nevents)
			    periodic_chores();

			healthd_mode_ops->heartbeat();

			mode_timeout = healthd_mode_ops->preparetowait();
			if (timeout < 0 || (mode_timeout > 0 && mode_timeout < timeout))
			    timeout = mode_timeout;
			nevents = epoll_wait(epollfd, events, eventct, timeout);
			if (nevents == -1) {
			    if (errno == EINTR)
				continue;
			    KLOG_ERROR(LOG_TAG, "healthd_mainloop: epoll_wait failed\n");
			    break;
			}

			for (int n = 0; n < nevents; ++n) {
			    if (events[n].data.ptr)
				(*(void (*)(int))events[n].data.ptr)(events[n].events);
			}
		    }

		    return;
		}
	healthd_register_event()
		定义:system/core/healthd/include/healthd/healthd.h
			int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup = EVENT_NO_WAKEUP_FD);
		实现:system/core/healthd/healthd.cpp
			int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup) { }
		注册的事件有:前面2个中选择一个,由healthd_mode_ops决定。
			system/core/healthd/healthd_mode_charger.cpp  ::    healthd_register_event(epollfd, charger_event_handler, EVENT_WAKEUP_FD);
			system/core/healthd/healthd_mode_android.cpp  ::    if (healthd_register_event(gBinderFd, binder_event))
			system/core/healthd/healthd.cpp  ::  if (healthd_register_event(uevent_fd, uevent_event, EVENT_WAKEUP_FD))
			system/core/healthd/healthd.cpp  ::  if (healthd_register_event(wakealarm_fd, wakealarm_event, EVENT_WAKEUP_FD))

	gBatteryMonitor = new BatteryMonitor();
		BatteryMonitor::BatteryMonitor() : mHealthdConfig(nullptr), mBatteryDevicePresent(false),
		    mAlwaysPluggedDevice(false), mBatteryFixedCapacity(0), mBatteryFixedTemperature(0) {
		    initBatteryProperties(&props);
		}
		static void initBatteryProperties(BatteryProperties* props) {
		    props->chargerAcOnline = false;
		    props->chargerUsbOnline = false;
		    props->chargerWirelessOnline = false;
		    props->maxChargingCurrent = 0;
		    props->maxChargingVoltage = 0;
		    props->batteryStatus = BATTERY_STATUS_UNKNOWN;
		    props->batteryHealth = BATTERY_HEALTH_UNKNOWN;
		    props->batteryPresent = false;
		    props->batteryLevel = 0;
		    props->batteryVoltage = 0;
		    props->batteryTemperature = 0;
		    props->batteryCurrent = 0;
		    props->batteryCycleCount = 0;
		    props->batteryFullCharge = 0;
		    props->batteryChargeCounter = 0;
		    props->batteryTechnology.clear();
		}
	gBatteryMonitor->init(&healthd_config);
从SystemServer.java:startOtherServices()处调用过来
InputManagerService inputManager = new InputManagerService(context);
 /*
 * Wraps the C++ InputManager and provides its callbacks.
 */
public class InputManagerService extends IInputManager.Stub
        implements Watchdog.Monitor {
    // Pointer to native input manager service object.
    private final long mPtr;

    private final Context mContext;
    private final InputManagerHandler mHandler;
    private WindowManagerCallbacks mWindowManagerCallbacks;
    private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
    private boolean mSystemReady;
    private NotificationManager mNotificationManager;

   public InputManagerService(Context context) {
        this.mContext = context;
        this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());

        /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
    final boolean mUseDevInputEventForAudioJack =
                context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
        Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
                + mUseDevInputEventForAudioJack);
        mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());

        LocalServices.addService(InputManagerInternal.class, new LocalService());
    }
接下来是Native层的InputManager
	com_android_server_input_InputManagerService.cpp
	static jlong nativeInit(JNIEnv* env, jclass clazz,
		jobject serviceObj, jobject contextObj, jobject messageQueueObj) {
	    sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
	    if (messageQueue == NULL) {
		jniThrowRuntimeException(env, "MessageQueue is not initialized.");
		return 0;
	    }

	    NativeInputManager* im = new NativeInputManager(contextObj, serviceObj, messageQueue->getLooper());
	    im->incStrong(0);
	    return reinterpret_cast<jlong>(im);
	}
		sp<MessageQueue> android_os_MessageQueue_getMessageQueue(JNIEnv* env, jobject messageQueueObj) {
		    jlong ptr = env->GetLongField(messageQueueObj, gMessageQueueClassInfo.mPtr);
		    return reinterpret_cast<NativeMessageQueue*>(ptr);
		}
	NativeInputManager::NativeInputManager(jobject contextObj,
		jobject serviceObj, const sp<Looper>& looper) :	sp<Looper> mLooper(looper), volatile bool mInteractive(true) {
	    JNIEnv* env = jniEnv();

	    jobject mContextObj = env->NewGlobalRef(contextObj);
	    jobject mServiceObj = env->NewGlobalRef(serviceObj);

	    {
		AutoMutex _l(mLock);
		mLocked.systemUiVisibility = ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE;
		mLocked.pointerSpeed = 0;
		mLocked.pointerGesturesEnabled = true;
		mLocked.showTouches = false;
		mLocked.hardwareRotation = 0;
		    char property[PROPERTY_VALUE_MAX];
		if (property_get("ro.sf.hwrotation", property, "0") > 0) {
		    mLocked.hardwareRotation = atoi(property) / 90;
		}
	    }

	    sp<EventHub> eventHub = new EventHub(); class EventHub : public EventHubInterface
	    sp<InputManager> mInputManager = new InputManager(eventHub, this, this);
	}
		InputManager::InputManager(
			const sp<EventHubInterface>& eventHub,
			const sp<InputReaderPolicyInterface>& readerPolicy,
			const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
		    sp<InputDispatcherInterface> mDispatcher = new InputDispatcher(dispatcherPolicy);
			class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
			class InputListenerInterface : public virtual RefBase {
				protected:
				    InputListenerInterface() { }
				    virtual ~InputListenerInterface() { }

				public:
				    virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) = 0;
				    virtual void notifyKey(const NotifyKeyArgs* args) = 0;
				    virtual void notifyMotion(const NotifyMotionArgs* args) = 0;
				    virtual void notifySwitch(const NotifySwitchArgs* args) = 0;
				    virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args) = 0;
				};
		        //sp<InputDispatcherThread> mDispatcherThread;
		    sp<InputReaderInterface> mReader = new InputReader(eventHub, readerPolicy, mDispatcher); 
			class InputReaderInterface : public virtual RefBase {
			//sp<InputReaderThread> mReaderThread;
		    initialize();
		}
		void InputManager::initialize() {
		    mReaderThread = new InputReaderThread(mReader);
		    mDispatcherThread = new InputDispatcherThread(mDispatcher);
		}
    /**
     * Private handler for the input manager.
     */
    private final class InputManagerHandler extends Handler {
        public InputManagerHandler(Looper looper) {
            super(looper, null, true /*async*/);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) { 从1-5
                case MSG_DELIVER_INPUT_DEVICES_CHANGED:
                    deliverInputDevicesChanged((InputDevice[])msg.obj);
                    break;
                case MSG_SWITCH_KEYBOARD_LAYOUT:
                    handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
                    break;
                case MSG_RELOAD_KEYBOARD_LAYOUTS:
                    reloadKeyboardLayouts();
                    break;
                case MSG_UPDATE_KEYBOARD_LAYOUTS:
                    updateKeyboardLayouts();
                    break;
                case MSG_RELOAD_DEVICE_ALIASES:
                    reloadDeviceAliases();
                    break;
            }
        }
    }

    private final class LocalService extends InputManagerInternal {
        @Override
        public void setDisplayViewports(
                DisplayViewport defaultViewport, DisplayViewport externalTouchViewport) {
            setDisplayViewportsInternal(defaultViewport, externalTouchViewport);
        }

        @Override
        public boolean injectInputEvent(InputEvent event, int displayId, int mode) {
            return injectInputEventInternal(event, displayId, mode);
        }

        @Override
        public void setInteractive(boolean interactive) {
            nativeSetInteractive(mPtr, interactive);
        }
    }
	
    public abstract class InputManagerInternal {
	    public abstract boolean injectInputEvent(InputEvent event, int displayId, int mode);

	    /**
	     * Called by the display manager to set information about the displays as needed
	     * by the input system.  The input system must copy this information to retain it.
	     */
	    public abstract void setDisplayViewports(DisplayViewport defaultViewport,
		    DisplayViewport externalTouchViewport);

	    /**
	     * Called by the power manager to tell the input manager whether it should start
	     * watching for wake events.
	     */
	    public abstract void setInteractive(boolean interactive);
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值