How to tell if android device detected by ADB?

2019-04-16 05:14发布

I am using ADB to push files from my java application to a tablet when its connected via USB. I would like to be able to detect if a device is connected or not via USB by ADB. The code I am using to push the files across is:

public void wiredsync(){
        try {
            abdsourcesync = buildpath; 
            adbtabletsync = "/mnt/sdcard/test"; 
            System.out.println("Starting Sync via adb with command " + "adb" + " push "+ buildpath + " " + adbtabletsync);
                    Process process = Runtime.getRuntime().exec("adb" + " push "+ buildpath + " " + adbtabletsync);
                    InputStreamReader reader = new InputStreamReader(process.getInputStream());
                    Scanner scanner = new Scanner(reader);
                    scanner.close();
                } catch(IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }//end wiredsync

How can I modify this code to work out if a tablet is connected or not?

Thanks for the help.

Andy

标签: java adb
1条回答
我命由我不由天
2楼-- · 2019-04-16 05:53

By using ddmlib.jar, which is also used by Eclipse plugins, you can monitor the device connect/disconnect event. The ddmlib is usually found in the tools/lib directory in Android SDK. But there is no the official documents about how to use it. Below is the code example. You have to include the ddmlib.jar and change the adb location according to your environment.

import java.io.IOException;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
import com.android.ddmlib.IDevice;

public class Main {

    public static void main(String[] args) throws IOException {
        AndroidDebugBridge.init(false);

        AndroidDebugBridge debugBridge = AndroidDebugBridge.createBridge("D:\\android-sdk\\platform-tools\\adb.exe", true);
        if (debugBridge == null) {
            System.err.println("Invalid ADB location.");
            System.exit(1);
        }

        AndroidDebugBridge.addDeviceChangeListener(new IDeviceChangeListener() {

            @Override
            public void deviceChanged(IDevice device, int arg1) {
                // not implement
            }

            @Override
            public void deviceConnected(IDevice device) {
                System.out.println(String.format("%s connected", device.getSerialNumber()));
            }

            @Override
            public void deviceDisconnected(IDevice device) {
                System.out.println(String.format("%s disconnected", device.getSerialNumber()));

            }

        });

        System.out.println("Press enter to exit.");
        System.in.read();
    }
}
查看更多
登录 后发表回答