在某些设备上发现 p2p 连接的对等点失败,在某些设备上它如何失败?

问题描述

这是我的代码,它在设备 realme c12 上运行良好并发现可用设备,但在 realme3i 上失败。还建议我在服务器端和客户端连接,如何通过套接字编程连接。

   public class DiscoverActivity extends AppCompatActivity {


    LottieAnimationView discoverani;
    Handler discoveranimae = new Handler();
    WifiP2pManager manager;
    WifiP2pManager.Channel channel;
    BroadcastReceiver receiver;
    CustomAdapterForDiscoveredDevice customAdapterForDiscoveredDevice;
    public static ArrayList<WifiP2pDevice> peerslist = new ArrayList<WifiP2pDevice>();
    public static String[] devisename;
    WifiP2pDevice[] deviceslist;
    RecyclerView recyclerView;
    IntentFilter intentFilter;
    CustomAdapterForDiscoveredDevice.RecycleDeviceonclick listner;
    TextView deviceStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discover);

        recyclerView = findViewById(R.id.devicesdiscovered);
        deviceStatus = findViewById(R.id.deviceStatus);
        deviceStatus.setText("Discovery Started");
        discoverani = findViewById(R.id.discoveranimae);
        Thread thread1 = new Thread() {

            @Override
            public void run() {
                super.run();
                discoveranimae.post(new Runnable() {
                    @Override
                    public void run() {

                        discoverani.playAnimation();

                    }
                });

            }
        };
        thread1.start();

        manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(this,getMainLooper(),null);
        receiver = new WifiDirectBroadcastReceiver(manager,channel,this);

        intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        registerReceiver(receiver,intentFilter);

        if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions,and then overriding
            //   public void onRequestPermissionsResult(int requestCode,String[] permissions,//                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        manager.discoverPeers(channel,new WifiP2pManager.ActionListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onSuccess() {

                Log.d("Discovery","Started");
                // manager.requestPeers(channel,peerListListener);


            }

            @Override
            public void onFailure(int reason) {

                Log.d("Discovery","Failed");


            }
        });


    }

    WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peers) {

            if (!peers.getDeviceList().equals(peerslist)) {
                peerslist.clear();
                peerslist.addAll(peers.getDeviceList());
                devisename = new String[peers.getDeviceList().size()];
                deviceslist = new WifiP2pDevice[peers.getDeviceList().size()];
                int index = 0;
                for (WifiP2pDevice device : peers.getDeviceList()) {

                    devisename[index] = device.deviceName;
                    deviceslist[index] = device;
                    index++;

                }

                setOnClicklistner();
                customAdapterForDiscoveredDevice = new CustomAdapterForDiscoveredDevice(DiscoverActivity.this,listner);
                StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
                recyclerView.setLayoutManager(staggeredGridLayoutManager);
                recyclerView.setAdapter(customAdapterForDiscoveredDevice);
                Log.d("number of device found",String.valueOf(devisename.length));

            }
            if (peerslist.size() == 0) {
                Toast.makeText(getApplicationContext(),"No Device Found",Toast.LENGTH_LONG).show();
                return;
            }

        }
    };

    private void setOnClicklistner() {

        listner = new CustomAdapterForDiscoveredDevice.RecycleDeviceonclick() {
            @Override
            public void Onclick(View itemView,final int adapterPosition) {

                Toast.makeText(getApplicationContext(),devisename[adapterPosition],Toast.LENGTH_SHORT).show();
                WifiP2pDevice device = deviceslist[adapterPosition];
                WifiP2pConfig config = new WifiP2pConfig();
                config.deviceAddress = device.deviceAddress;

                if (ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions,and then overriding
                    //   public void onRequestPermissionsResult(int requestCode,//                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                manager.connect(channel,config,new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {

                        Toast.makeText(getApplicationContext(),"connected to"+devisename[adapterPosition],Toast.LENGTH_SHORT).show();



                    }

                    @Override
                    public void onFailure(int reason) {
                        Toast.makeText(getApplicationContext(),"failed to connected to"+devisename[adapterPosition],Toast.LENGTH_SHORT).show();


                    }
                });


            }
        };

    }

    WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo info) {

            final InetAddress inetAddress=info.groupOwnerAddress;
            if(info.groupFormed && info.isGroupOwner){

                deviceStatus.setText("Host");

            }
            else if(info.groupFormed){

                deviceStatus.setText("Client");
            }

        }
    };


    @Override
            protected void onResume() {
                super.onResume();
        registerReceiver(receiver,intentFilter);

            }

            @Override
            protected void onPause() {
                super.onPause();

                unregisterReceiver(receiver);

            }
}

我希望我提供了足够的细节,请提出建议。为什么在某些特定设备上它会失败,我试图从 logcat 了解,但他们没有任何详细信息

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...