上篇文章讲了PC与android手机连接的办法 ,通过java调用系统命令执行adb命令操作,实际上是一个比较笨的办法。

网上查阅资料,发现google 提供了ddmlib库 (adt-bundle\sdk\tools 目录下), 提供了adb相关操作的所有api。

文档参考

http://www.jarvana.com/jarvana/view/com/google/android/tools/ddmlib/r13/ddmlib-r13-javadoc.jar!/index.html

参考范例如下

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();  
        }  
    }  
}

转自:http://blog.csdn.net/wsdx/article/details/9420707

利用ddmlib 实现 PC端与android手机端adb forword socket通信(转)的更多相关文章

  1. TODO monkey笔记,PC端执行和手机端执行

    微博不给力啊 吞我笔记,还好我有txt... 1.环境准备:安装Android sdk, 配置环境变量:platfrom_tools,tools,aapt;java:2.查询当前apk信息: aapt ...

  2. H.264视频在android手机端的解码与播放(转)

    随着无线网络和智能手机的发展,智能手机与人们日常生活联系越来越紧密,娱乐.商务应用.金融应用.交通出行各种功能的软件大批涌现,使得人们的生活丰富多彩.快捷便利,也让它成为人们生活中不可取代的一部分.其 ...

  3. PHP判断客户端是PC web端还是移动手机端方法

    PHP判断客户端是PC web端还是移动手机端方法需要实现:判断手机版的内容加上!c550x260.jpg后缀变成缩略图PHP用正则批量替换Img中src内容,用正则表达式获取图片路径实现缩略图功能 ...

  4. pc端和android端应用程序测试有什么区别?(ps面试题)

    pc端和android端应用程序测试有什么区别?(ps面试题) [VIP7]大连-凭海临风(215687736) 2014/4/10 8:56:171.测试环境不同PC平台一般都是windows an ...

  5. PC端的软件端口和adb 5037端口冲突解决方案

    引用https://www.aliyun.com/jiaocheng/32552.html 阿里云 >  教程中心   >  android教程 >  PC端的软件端口和adb 50 ...

  6. PC端使用opencv获取webcam,通过socket把Mat图像传输到android手机端

    demo效果图: PC端 android端 大体流程 android端是服务器端,绑定IP和端口,监听来自PC端的连接, pc端通过socket与服务器andorid端传输图片. 主要代码 andro ...

  7. 利用jQuery实现PC端href生效,移动端href失效

    今天要写一个功能,记录一下吧.if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){ $('.item-a').attr('href' ...

  8. pc端前端和手機端區別

    1.pc端寬度比較固定,手機端可以橫屏或者豎屏: 2.pc端不需要處理手機觸摸,而手機端需要: 3.pc端不需要處理鍵盤事件: 3.pc的瀏覽器內核很多,手機端基本上是webkit或者是基於webki ...

  9. Android 手机端自动化测试框架

    前言: 大概有4个月没有更新了,因项目和工作原因,忙的手忙脚乱,趁十一假期好好休息一下,年龄大了身体还是扛不住啊,哈哈.这次更新Android端自动化测试框架,也想开源到github,这样有人使用才能 ...

随机推荐

  1. mac下为Apache 创建 .htaccess文件

    标签:mac   .htaccess 在设置固定链接时会提示如下的问题:   若您的 .htaccess 文件可写,我们可以自动修改它.但似乎它不可写,因此我们在下方列出了您 .htaccess 文件 ...

  2. 改变WPF ListBoxItem的选中样式

    想用ListBox作一个类似IOS 设置的菜单,却发现很难改变ListBoxItem鼠标移过.选中的默认蓝色背景与边框. 尝试使用Style来设置strigger,依然不成功.在百度搜索一些资料,提到 ...

  3. Http error code

    概要 当用户试图通过HTTP或文件传输协议(FTP)访问一台正在运行Internet信息服务(IIS)的服务器上的内容时,IIS返回一个表示该请求的状态的数字代码.该状态代码记录在IIS日志中,同时也 ...

  4. 转:Android中Context详解 ---- 你所不知道的Context

    转:http://blog.csdn.net/qinjuning/article/details/7310620 转:http://blog.csdn.net/lmj623565791/article ...

  5. Linux 字符设备驱动模型

    一.使用字符设备驱动程序 1. 编译/安装驱动 在Linux系统中,驱动程序通常采用内核模块的程序结构来进行编码.因此,编译/安装一个驱动程序,其实质就是编译/安装一个内核模块 2. 创建设备文件 通 ...

  6. Linux之查看文件大小

    1.查看当前文件大小du -sh ./ du [-abcDhHklmsSx] [-L <符号连接>][-X <文件>][--block-size][--exclude=< ...

  7. xhtml+css基础知识1

    样式 行间样式:在标签里 <div style="width:400px; height:200px; background:red;">块</div> 内 ...

  8. 关于HTML中浮动与清除的思考

    布局时需要利用浮动(float)的属性,同时我们需要一个清除浮动(clear)与之配合才能达到预期的目标. w3s上关于float和clear的定义分别为:float:float 属性定义元素在哪个方 ...

  9. CS异步下载

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  10. Part 13 Create a custom filter in AngularJS

    Custom filter in AngularJS 1. Is a function that returns a function 2. Use the filter function to cr ...