奇怪的反思错误

时间:2015-03-10 21:26:03

标签: java android reflection wireless peer

我已经尝试了几周的解决方法/解决这个问题,我似乎无法再解决这个问题了。我有一个Android应用程序需要在创建对等网络之前更改设备的名称。

因为该方法隐藏在Android的SDK中,所以我使用的是反射。我想要反映的方法位于第1305行:https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/wifi/java/android/net/wifi/p2p/WifiP2pManager.java

这是我的代码尝试反射:

public class HostStagingActivity extends Activity
{
WifiP2pManager.Channel myChannel; //This channel is created and passed to system services in order for WIFI_P2P to work
WifiP2pManager myManager; //This manager is declared to get the required channel object
...

@Override
protected void onCreate(Bundle savedInstanceState)
{
myManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);//passed to the myReceiver listener class
myChannel = myManager.initialize(this, getMainLooper(), null);//passed to the myReceiver listener class
...
Method method1 = null;    
try
        {
            method1 = myManager.getClass().getMethod("setDeviceName",  new Class[] {WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class });
            method1.invoke(myChannel, NETWORK_NAME, new WifiP2pManager.ActionListener()
            {
                public void onSuccess()
                {
                    Toast.makeText(getApplicationContext(), "DeviceName Changed Successfully!", Toast.LENGTH_SHORT).show();
                    //Code for Success in changing name
                }
                public void onFailure(int reason)
                {
                    Toast.makeText(getApplicationContext(), "DeviceName Change Returned Failure!", Toast.LENGTH_SHORT).show();
                    //Code to be done while name change Fails
                }
            });
        }

但是,这会导致运行时错误:

Caused by: java.lang.IllegalArgumentException: expected receiver of type android.net.wifi.p2p.WifiP2pManager, but got android.net.wifi.p2p.WifiP2pManager$Channel
            at java.lang.reflect.Method.invokeNative(Native Method)

当我在代码中明确传递WifiP2pManager.Channel类时,为什么该方法需要WifiP2pManager对象?只是为了好玩,当我通过它所预期的争论时,它声称该方法期待三个争论而我只给了它两个。

任何有更多反思经验的人都可以帮助我吗?

0 个答案:

没有答案