wifi p2p系统中本机名称WifiP2pDevice.deviceName是由系统指定的,直接修改并不能起作用。WifiP2pManager类中有设备名称设置方法setDeviceName,可以改变本设备名称。
/**
* Set p2p device name.
* @hide
* @param c is the channel created at {@link #initialize}
* @param listener for callback when group info is available. Can be null.
*/
@UnsupportedAppUsage
public void setDeviceName(Channel c, String devName, ActionListener listener) {
checkChannel(c);
WifiP2pDevice d = new WifiP2pDevice();
d.deviceName = devName;
c.mAsyncChannel.sendMessage(SET_DEVICE_NAME, 0, c.putListener(listener), d);
}
但是这个方法是 @UnsupportedAppUsage的,不能在app中直接使用。无奈只好用反射机制取得该方法,kotlin代码如下:
private fun setDeviceName(deviceName: String) {
try {
val paramTypes0 = WifiP2pManager.Channel::class.java
val paramTypes1 = String::class.java
val paramTypes2 = WifiP2pManager.ActionListener::class.java
val setDeviceName: Method = wifiP2pManager.javaClass.getMethod(
"setDeviceName", paramTypes0, paramTypes1, paramTypes2
)
setDeviceName.isAccessible = true
setDeviceName.invoke(wifiP2pManager, channel,
deviceName,
object : WifiP2pManager.ActionListener {
override fun onSuccess() {
Log.i(thisTag, "setDeviceName succeeded")
}
override fun onFailure(reason: Int) {
Log.i(thisTag, "setDeviceName failed")
}
})
} catch (e: NoSuchMethodException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: IllegalArgumentException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
}
}
其中两个变量wifiP2pManager、channel是WifiP2pManager和WifiP2pManager.Channel的实例,需要在app中取得。
wifiP2pManager = app.getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
channel = wifiP2pManager.initialize(app, Looper.getMainLooper(), this)
setDeviceName的时机通常是取得wifiP2pManager、channel之后。
|