Java Reflection 機制, 以 DisplayManager 為例

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值