【问题标题】:How to WifiP2pDevice.deviceName for current device?如何为当前设备设置 WifiP2pDevice.deviceName?
【发布时间】:2018-12-04 07:11:57
【问题描述】:

我知道有人问过类似的问题,但答案对我不起作用。我尝试了this 答案,但它引发了空指针异常。我也看到了this 的回答,但是 WifiP2pManager 没有任何返回设备名称的属性或方法。

有人可以帮忙吗?

我基本上想向用户显示他们的设备名称,如果他们想设置自定义名称,让他们更改它。

谢谢。

【问题讨论】:

    标签: android wifi-direct


    【解决方案1】:

    如果您仍在寻找答案,方法如下:

    1. 识别自己的设备名称

    在您的广播接收器中接收到WIFI_P2P_THIS_DEVICE_CHANGED_ACTION 意图后,这将变为可用。只需像这样使用deviceName 成员变量:

    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
    
      if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
    
        WifiP2pDevice self = (WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
    
        // Now self.deviceName gives you own device name
    
      } else if(WifiP2pManager.WIFI_P2P...) {
      ...
    


    2.更改自己的设备名称

    根据开发者文档,没有使用WifiP2pManager 更改设备名称的方法,尽管源代码中存在公共setDeviceName() 方法,但您不能在您的对象上调用它(可能是为了保留开发人员从代表附近对等设备的对象上调用它)。对我有用的是获得一个代表所述方法的Method 对象并在我的WifiP2pManager 实例上调用它:

    private WifiP2pManager manager;
    private WifiP2pManager.Channel channel;
    
    ...
    
    public void changeDeviceName(String deviceNewName) {
      try {
        Method method = manager.getClass().getMethod("setDeviceName", WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);
    
        method.invoke(manager, channel, deviceNewName, new WifiP2pManager.ActionListener() {
    
          @Override
          public void onSuccess() {
            Toast.makeText(MainActivity.this, "Name successfully changed", Toast.LENGTH_LONG).show();
          }
    
          @Override
          public void onFailure(int reason) {
            Toast.makeText(MainActivity.this, "Request failed: " + reason, Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Name change failed: " + reason);
          }
        });
    
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    

    或者,用户可以从高级 WiFi 设置(首选项 > 高级 > WiFi Direct > 配置设备)手动重命名他们的设备,

    编辑:从 Pie 开始,使用非 SDK 接口(本质上是标有 @hide 的类、变量或方法,您可以使用反射访问)受到限制,最终将被禁止。上述方法目前已列入灰名单(这意味着将来可能会删除对反映它的支持)。在此处阅读更多信息:https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多