为什么我的Android TCP客户端应用程序不能在其他手机上工作?

时间:2015-12-20 10:36:34

标签: android tcp android-version android-min-sdk target-sdk

我使用的是安卓版4.1.1的Android手机。 .IT工作正常。我可以通过TCP / IP将这个手机的字符串数据传输到我的PC上的VB应用程序。但是,如果我使用我的另一部手机,使用Android版本4.4.4 kitkat ..我仍然可以正确安装.apk文件并运行它..但它不会执行其功能,同样适用于我的其他手机4.0.1。

这是我的代码:

XML文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="hello"
    />
<EditText
    android:id="@+id/textout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<Button
    android:id="@+id/buttonSend"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send"
    />
<TextView
    android:id="@+id/textin"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

JAVA文件:

public class MainActivity extends Activity {

EditText textOut;
TextView textIn;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textOut = (EditText)findViewById(R.id.textout);
    Button buttonSend = (Button)findViewById(R.id.buttonSend);
    textIn = (TextView)findViewById(R.id.textin);
    buttonSend.setOnClickListener(buttonSendOnClickListener);




}

Button.OnClickListener buttonSendOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View arg0) {

        // TODO Auto-generated method stub
        Socket socket = null;
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;

        try{
            // Creating new socket connection to the IP (first parameter) and its opened port (second parameter)
            Socket s = new Socket("192.168.1.3", 65535);

            // Initialize output stream to write message to the socket stream
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

            String outMsg = "";

            outMsg = textOut.getText().toString();

            // Write message to stream
            out.write(outMsg);

            // Flush the data from the stream to indicate end of message
            out.flush();

            // Close the output stream
            out.close();

            // Close the socket connection
            s.close();
        }

        catch(Exception ex){
            //:TODO Handle exceptions
        }
    }};

}

它与API级别有关吗? minsdkversion和targetsdkversion? 请帮助我...即将疯狂。 HAHA XD提前致谢。

1 个答案:

答案 0 :(得分:1)

您无法在单击处理程序中创建套接字连接。您将拥有NetworkOnMainThreadException。将这些代码放在一个线程或AsyncTask中。

您的代码也不适用于4.1.1。