Java Reflection 機制, 以 DisplayManager 為例

来源:互联网 发布:php foreach遍历数组 编辑:程序博客网 时间:2024/06/06 00:30

DisplayManager 有很多隱藏方法, 如scanWifiDisplays, connectWifiDisplay, disconnectWifiDisplay. 我們今天就來試試如何調用.


1.

    private Handler mWfdHandler = new Handler();
    
    //suport scan, connect
   public class WfdMethod implements Runnable {
        // Time between wifi display scans when actively scanning in milliseconds.
        //private static final int WIFI_DISPLAY_SCAN_INTERVAL = 15000;
        Method mMethod = null;
        String mArg = null;
        boolean bResult = false;
        public WfdMethod( String szMethod, String szArg) {
            try{
                if(szMethod == "scan"){
                    mMethod = DisplayManager.class.getMethod("scanWifiDisplays");
                    mArg = null;
                }
                else if(szMethod == "connect")
                {
                     mMethod = DisplayManager.class.getMethod("connectWifiDisplay",new Class[]{String.class} );
                    mArg = szArg;
                   
                }
                   else if(szMethod == "disconnect")
                {
                     mMethod = DisplayManager.class.getMethod("disconnectWifiDisplay" );
                    mArg = null;
                   
                }                
            }
            catch(NoSuchMethodException e){
                Log.d(TAG, e.toString());                    

            }
            
        }

        
        @Override
        public void run() {
            DisplayManager displayManager = (DisplayManager)m_parent.getSystemService(Context.DISPLAY_SERVICE);
            
            try{
                Log.d(TAG, "running "+ mMethod.toString());
                if(mArg == null)
                    mMethod.invoke(displayManager );
                else
                    mMethod.invoke(displayManager,new Object[] {mArg} );                    
            }
            catch(IllegalAccessException e)
            {
                Log.d(TAG, e.toString());
             
            }
            catch(InvocationTargetException e){
                Log.d(TAG, e.toString());    
                 
            }
            catch( IllegalArgumentException e)
            {
                Log.d(TAG, e.toString());
             
            }                
            bResult = true;
        }

   }   


2. 調用

        mWfdHandler.postDelayed(new WfdMethod("scan", null), 0);        

        mWfdHandler.postDelayed(new WfdMethod("connect", deviceAddress), 0);         

        mWfdHandler.postDelayed(new WfdMethod("disconnect", null), 0);



0 0