草庐IT

android - 如何使用 USB 将消息从 Android 发送到 Windows

coder 2023-11-19 原文

我是 Android 的完全菜鸟,仅在按钮激活的基本(1 或 2 行) Activity 级别上,但我想创建一个非常简单的应用程序,当我点击应用程序图标时,它会触发并忘记向我的 Windows 8 PC 上的监听服务器发送消息。电话作为简单的媒体设备连接,没有 Kies,通过 USB 数据线连接。

我可以得到一个消息框说谎并说消息已发送。我需要知道使用哪种通信 channel ,例如一个 COM 端口或什么,以及如何从 Android 通过它发送数据。在 Windows 方面,一旦我确定了如何通信,我就可以帮助自己。

最佳答案

从这个应用程序的桌面端开始: 您可以使用 ADB(Android 调试桥)通过设备和桌面之间的端口建立 tcp/ip 套接字连接。命令是:

adb forward tcp:<port-number> tcp:<port-number>

要在您的 java 程序中运行此命令,您必须创建一个进程构建器,其中此命令在子 shell 上执行。

对于 Windows,您可能需要使用:

process=Runtime.getRuntime().exec("D:\\Android\\adt-bundle-windows-x86_64-20130729\\sdk\\platform-tools\\adb.exe forward tcp:38300 tcp:38300");
        sc = new Scanner(process.getErrorStream());
        if (sc.hasNext()) 
        {
            while (sc.hasNext()) 
                System.out.print(sc.next()+" ");
            System.out.println("\nCannot start the Android debug bridge");
        }
        sc.close();
        }

执行adb命令所需的函数:

String[] commands = new String[]{"/bin/sh","-c", command};
        try {
            Process proc = new ProcessBuilder(commands).start();
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String s = null;
            while ((s = stdInput.readLine()) != null) 
            {
                sb.append(s);
                sb.append("\n");
            }
            while ((s = stdError.readLine()) != null) 
            {
                sb.append(s);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

上述方法会将上述命令作为字符串并在子 shell 上执行

  //Extracting Device Id through ADB
    device_list=CommandExecutor.execute("adb devices").split("\\r?\\n");
    System.out.println(device_list);
    if(device_list.length>1)
    {
        if(device_list[1].matches(".*\\d.*"))
        {
            device_id=device_list[1].split("\\s+");
            device_name=""+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.manufacturer")+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.model");
            device_name=device_name.replaceAll("\\s+"," ");
            System.out.println("\n"+device_name+" : "+device_id[0]);
            device=device_id[0];
            System.out.println("\n"+device);

        }
        else
        {
            System.out.println("Please attach a device");

        }
    }
    else
    {
        System.out.println("Please attach a device");

    }

CommandExecutor 是一个包含 execute 方法的类。 execute 方法的代码与上面发布的代码相同。 这将检查是否有任何设备已连接,如果已连接,它将返回唯一的 ID 号。

最好在执行 adb 命令时使用 id 号码,例如:

adb -s "+device_id[0]+" shell getprop ro.product.manufacturer 

adb -s <put-id-here> shell getprop ro.product.manufacturer

请注意,在 adb 之后必须使用 '-s'。

然后使用 adb forward 命令你需要建立一个 tcp/ip 套接字。这里桌面将是客户端,移动/设备将是服务器。

//Create socket connection
    try{
        socket = new Socket("localhost", 38300);
        System.out.println("Socket Created");
        out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hey Server!\n");

        new Thread(readFromServer).start();
        Thread closeSocketOnShutdown = new Thread() {
            public void run() {
                try {
                    socket.close();
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
    } 
    catch (UnknownHostException e) {
        System.out.println("Socket connection problem (Unknown host)"+e.getStackTrace());
    } catch (IOException e) {
        System.out.println("Could not initialize I/O on socket "+e.getStackTrace());
    }

然后你需要从服务器读取,即设备:

private Runnable readFromServer = new Runnable() {

    @Override
    public void run() {
try {
            System.out.println("Reading From Server");
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while ((buffer=in.readLine())!=null) {
                System.out.println(buffer);
    }catch (IOException e) {
            try {
                in.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

“缓冲区”将包含设备将从其应用端发送的内容。

现在在您的移动应用程序中,您将需要打开相同的连接并将数据简单地写入缓冲区

public class TcpConnection implements Runnable {

public static final int TIMEOUT=10;
private String connectionStatus=null;
private Handler mHandler;
private ServerSocket server=null; 
private Context context;
private Socket client=null;
private String line="";
BufferedReader socketIn;
PrintWriter socketOut;


public TcpConnection(Context c) {
    // TODO Auto-generated constructor stub
    context=c;
    mHandler=new Handler();
}

@Override
public void run() {
    // TODO Auto-generated method stub


    // initialize server socket
        try {
            server = new ServerSocket(38300);
            server.setSoTimeout(TIMEOUT*1000);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //attempt to accept a connection
            try{
                client = server.accept();

                socketOut = new PrintWriter(client.getOutputStream(), true);
                socketOut.println("Hey Client!\n");
                socketOut.flush();

                syncContacts();

                Thread readThread = new Thread(readFromClient);
                readThread.setPriority(Thread.MAX_PRIORITY);
                readThread.start();
                Log.e(TAG, "Sent");
            }
            catch (SocketTimeoutException e) {
                // print out TIMEOUT
                connectionStatus="Connection has timed out! Please try again";
                mHandler.post(showConnectionStatus);
                try {
                    server.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } 
            catch (IOException e) {
                Log.e(TAG, ""+e);
            } 

            if (client!=null) {
                try{
                    // print out success
                    connectionStatus="Connection succesful!";
                    Log.e(TAG, connectionStatus);
                    mHandler.post(showConnectionStatus);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

}

private Runnable readFromClient = new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            Log.e(TAG, "Reading from server");
            socketIn=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while ((line = socketIn.readLine()) != null) {
                Log.d("ServerActivity", line);
                //Do something with line
            }
            socketIn.close();
            closeAll();
            Log.e(TAG, "OUT OF WHILE");
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
};

public void closeAll() {
    // TODO Auto-generated method stub
    try {
        Log.e(TAG, "Closing All");
        socketOut.close();
        client.close();
        server.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} 

private Runnable showConnectionStatus = new Runnable() {
    public void run() {
        try
        {
            Toast.makeText(context, connectionStatus, Toast.LENGTH_SHORT).show();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
};
   }
 }

关于android - 如何使用 USB 将消息从 Android 发送到 Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21748790/

有关android - 如何使用 USB 将消息从 Android 发送到 Windows的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  6. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  9. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  10. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

随机推荐