Есть ли способ программно обнаружить соединение ADB через WiFi? - PullRequest
1 голос
/ 01 декабря 2019

Я разрабатываю приложение, которое автоматически подключает клиентское устройство к серверу adb на компьютере (через wifi). Я застрял на обнаружении, успешно ли он подключен через Wi-Fi или нет. Есть ли такой способ прослушивания Java, который обнаруживает подключение к устройству по беспроводной сети?

mainactivity.java

    public class MainActivity extends AppCompatActivity {

    private Thread thread;

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

        // Check for Wireless connection


        // Check for USB connection
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    while (!thread.isInterrupted()) {
                        Thread.sleep(100);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(usbDebuggingConnected()){
                                    WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                                    assert manager != null;
                                    WifiInfo info = manager.getConnectionInfo();
                                    String address = info.getMacAddress();
                                    TextView t = findViewById(R.id.usb_connection);
                                    t.setText("Connected with the address - " + address);
                                    t.setTextColor(getResources().getColor(R.color.green));
                                } else {
                                    TextView t = findViewById(R.id.usb_connection);
                                    t.setText("USB Debugging Disconnected");
                                    t.setTextColor(getResources().getColor(R.color.red));
                                }
                            }
                        });
                    }
                } catch (InterruptedException ignored) {
                }
            }
        };
        thread.start();
    }

    public boolean usbDebuggingConnected() {
        Intent intent = registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
        assert intent != null;
        return Objects.requireNonNull(intent.getExtras()).getBoolean("connected");
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    style="@style/Theme.AppCompat.Transparent">

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.06">

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Wireless Connection Status:"
            android:textAlignment="center"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/wireless_connection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Disconnected"
            android:textAlignment="center"
            android:textColor="#D50000"
            android:textSize="18sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="USB Connection Status:"
            android:textAlignment="center"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/usb_connection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Disconnected"
            android:textAlignment="center"
            android:textColor="#D50000"
            android:textSize="18sp" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Спасибо впередвремени!

1 Ответ

0 голосов
/ 01 декабря 2019

Я нашел решение для этого. По сути, я заставляю приложение работать с TCP-клиентом с возможностью выбора порта. Я думаю, что вам нужно интегрировать ASyncTask, чтобы это работало. Я знаю, что нужно завершить 3-х стороннее рукопожатие, так что может быть что-то вроде широковещания, приема, подтверждения?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...