2014-07-20 119 views

回答

8

下面的Java代碼使用反射API,這是不太preferrable由於缺乏效率的,但是Android不提供另一種方式的話,你可以用它與魅力:

try { 
     Method m = wpm.getClass().getMethod(
       "setDeviceName", 
       new Class[] { WifiP2pManager.Channel.class, String.class, 
         WifiP2pManager.ActionListener.class }); 

     m.invoke(WifiP2pManager wifimngr,WifiP2pManager.Channel wifichannel, new_name, new WifiP2pManager.ActionListener() { 
      public void onSuccess() { 
       //Code for Success in changing name 
      } 

      public void onFailure(int reason) { 
       //Code to be done while name change Fails 
      } 
     }); 
    } catch (Exception e) { 

     e.printStackTrace(); 
    } 
+0

你可能會詳細說明並解釋爲什麼這段代碼會被刪除,以及它做了什麼?謝謝 – yochannah

6

此代碼對我的作品。

WifiP2pManager manager; 
WifiP2pManager.Channel channel; 
    try { 
     manager = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE); 
     channel = manager.initialize(this, getMainLooper(), new WifiP2pManager.ChannelListener() { 
      @Override 
      public void onChannelDisconnected() { 
       manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); 
      } 
     }); 
     Class[] paramTypes = new Class[3]; 
     paramTypes[0] = WifiP2pManager.Channel.class; 
     paramTypes[1] = String.class; 
     paramTypes[2] = WifiP2pManager.ActionListener.class; 
     Method setDeviceName = manager.getClass().getMethod(
       "setDeviceName", paramTypes); 
     setDeviceName.setAccessible(true); 

     Object arglist[] = new Object[3]; 
     arglist[0] = channel; 
     arglist[1] = devName; 
     arglist[2] = new WifiP2pManager.ActionListener() { 

      @Override 
      public void onSuccess() { 
       Log.d("setDeviceName succeeded", "true"); 
      } 

      @Override 
      public void onFailure(int reason) { 
       Log.d("setDeviceName failed", "true"); 
      } 
     }; 
     setDeviceName.invoke(manager, arglist); 

    } catch (NoSuchMethodException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
     e.printStackTrace(); 
    } 
+0

今天在Android 6.0.1上測試它 - 效果很好。謝謝。 –

+0

它的工作原理,是否有任何安全風險?那麼與WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION進行意圖廣播呢? – user3290180

相關問題