上篇文章讲了PC与android手机连接的办法 ,通过java调用系统命令执行adb命令操作,实际上是一个比较笨的办法。
网上查阅资料,发现google 提供了ddmlib库 (adt-bundle\sdk\tools 目录下), 提供了adb相关操作的所有api。
文档参考
参考范例如下
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.TimeoutException;
public class YingyonghuiHubServer {
public static final String TAG = "server";
public static int PC_LOCAL_PORT = 22222;
public static int PHONE_PORT = 22222;
public static String ADB_PATH = "adb.exe";
private static ADB mADB;
private static IDevice[] mDevices;
private static IDevice mDevice;
/**
* @param args
*/
public static void main(String[] args) {
mADB = new ADB();
mADB.initialize();
mDevices = mADB.getDevices();
mDevice = mDevices[0];
try {
mDevice.createForward(PC_LOCAL_PORT, PHONE_PORT);
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AdbCommandRejectedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initializeConnection();
}
static Socket socket;
public static void initializeConnection() {
// Create socket connection
try {
socket = new Socket("localhost", PC_LOCAL_PORT);
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject("lalala");
oos.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Socket connection problem (Unknown host)"
+ e.getStackTrace());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Could not initialize I/O on socket");
e.printStackTrace();
}
}
}
/*
* Copyright (C) 2009-2013 adakoda
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
public class ADB {
private AndroidDebugBridge mAndroidDebugBridge;
public boolean initialize() {
boolean success = true;
String adbLocation = System
.getProperty("com.android.screenshot.bindir");
// for debugging (follwing line is a example)
// adbLocation = "C:\\ ... \\android-sdk-windows\\platform-tools"; // Windows
// adbLocation = "/ ... /adt-bundle-mac-x86_64/sdk/platform-tools"; // MacOS X
if (success) {
if ((adbLocation != null) && (adbLocation.length() != 0)) {
adbLocation += File.separator + "adb";
} else {
adbLocation = "adb";
}
AndroidDebugBridge.init(false);
mAndroidDebugBridge = AndroidDebugBridge.createBridge(adbLocation,
true);
if (mAndroidDebugBridge == null) {
success = false;
}
}
if (success) {
int count = 0;
while (mAndroidDebugBridge.hasInitialDeviceList() == false) {
try {
Thread.sleep(100);
count++;
} catch (InterruptedException e) {
}
if (count > 100) {
success = false;
break;
}
}
}
if (!success) {
terminate();
}
return success;
}
public void terminate() {
AndroidDebugBridge.terminate();
}
public IDevice[] getDevices() {
IDevice[] devices = null;
if (mAndroidDebugBridge != null) {
devices = mAndroidDebugBridge.getDevices();
}
return devices;
}
}
手机端代码参考如下
package com.broadthinking.yingyonghuihubclinet;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final String TAG = "client";
public static int PHONE_PORT = 22222;
Context mContext = null;
TextView textView = null;
ServerSocket server = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = this;
this.textView = (TextView) this.findViewById(R.id.textView1);
try {
server = new ServerSocket(PHONE_PORT);
} catch (IOException e) {
e.printStackTrace();
return;
}
new RepackTestTask().execute();
}
private class RepackTestTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... params) {
Socket client = null;
// initialize server socket
while (true) {
try {
// attempt to accept a connection
client = server.accept();
Log.d(TAG, "Get a connection from "
+ client.getRemoteSocketAddress().toString());
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream());
String somewords = (String) ois.readObject();
Log.d(TAG, "Get some words" + somewords);
this.publishProgress(somewords);
client.close();
} catch (IOException e) {
Log.e(TAG, "" + e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
Toast.makeText(mContext, values[0].toString(), Toast.LENGTH_LONG)
.show();
}
}
}