几周以来,我一直在尝试解决方法/处理这个问题,但我似乎无法再解决它了。我有一个 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 对象?只是为了好玩,当我通过它期望的论点时,它声称该方法期望三个论点,而我只给了它两个。
有更多反思经验的人可以帮助我吗?