0

从这段代码中,我可以在 android 2.3.3.(Dell Streak) 中使用我的 PC 传输文件,但是当我在 android 4.2 (Samsung GS 3) 中运行相同的代码时,它什么也不做。我认为问题在于 Socket 何时初始化?我必须做什么才能在 4.2 中工作?

package com.hrandika.synchronizer.serverClient;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.os.AsyncTask;
import android.util.Log;

public class Client {

File sendingFile;

public Client(File sendingFile) {
    Log.d("Client", "Cleint : Constructed");
    this.sendingFile = sendingFile;
}

public void send(String ip) {
    try {
        Log.d("Client", "Cleint stating ....");
        Socket socket = new Socket(ip, 5555);
        Log.d("Client", "Cleint Socket Okay");

        OutputStream outputStream = socket.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                outputStream);

        Log.d("Client", "Cleint ready to sent");
        outputStreamWriter.write(sendingFile.getName() + "\n");
        outputStreamWriter.flush();
        Log.d("Client", "Cleint Sent");

        InputStream inputStream = socket.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(
                inputStream);

        BufferedReader bufferedReader = new BufferedReader(
                inputStreamReader);

        String serverResponse = bufferedReader.readLine();

        if (serverResponse.equals("READY")) {
            Log.d("Client", "Cleint : server ready");

            byte[] buffer = new byte[(int) sendingFile.length()];
            FileInputStream fileInputStream = new FileInputStream(
                    sendingFile);
            BufferedInputStream bufferedInputStream = new   BufferedInputStream(
                    fileInputStream);
            bufferedInputStream.read(buffer, 0, buffer.length);
            outputStream.write(buffer, 0, buffer.length);

            outputStream.flush();
            bufferedInputStream.close();
            fileInputStream.close();
            socket.close();

        }

    } catch (Exception e) {
    }
}



public class Sender extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... params) {
        send("192.168.43.21");
        return null;
    }

} 
} // End class Client
4

1 回答 1

0

您不得在 UI 线程上执行任何联网,这是由以 Honeycomb 开始的平台强制执行的。我想你没有AsyncTask正确使用。

必读:

更新:由于网络错误,开始adb shell(我假设设备通过 USB 连接到您的 PC)并输入telnet 192.168.43.21 5555- 这样您就可以检查您的服务器是否可以通过手机访问。

更新 2:刚刚检查过,恐怕telnet二进制文件在库存(非根)设备上不可用。但是任何可以连接到给定 IP/端口的应用程序都足以进行测试,例如这个telnet 客户端。通过这种方式,您甚至可以在接触自己的代码之前消除设置问题。

于 2012-11-28T12:17:21.483 回答