应用程序崩溃在3.0但在2.3.3中工作正常

时间:2012-05-30 10:22:38

标签: android sockets android-3.0-honeycomb

大家好我试图创建一个使用套接字连接的应用程序,我正在浏览一些示例,下面的代码片段工作正常,当我在2.3.3上运行它并在3.0中同样崩溃。

package com.simple.client;

import android.app.Activity;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Bundle;

public class SimpleClientActivity 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.main);
    textOut = (EditText)findViewById(R.id.textout);
    Button buttonSend = (Button)findViewById(R.id.send);
    textIn = (TextView)findViewById(R.id.textin);
    buttonSend.setOnClickListener(buttonSendOnClickListener);
}

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

public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;

try {
 socket = new Socket("172.16.2.172", 8899);
 dataOutputStream = new DataOutputStream(socket.getOutputStream());
 dataInputStream = new DataInputStream(socket.getInputStream());
 dataOutputStream.writeUTF(textOut.getText().toString());
 textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 e.printStackTrace();
}
finally{
 if (socket != null){
  try {
   socket.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 if (dataOutputStream != null){
  try {
   dataOutputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 if (dataInputStream != null){
  try {
   dataInputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   }
  }
 }
}};
}

我已经尝试了但都无法弄清楚发生了什么,

2 个答案:

答案 0 :(得分:2)

我的猜测是,由StrictMode.ThreadPolicy引起的错误。在android 3.0中,您无法在同一UI线程中访问网络。

答案 1 :(得分:1)

您的布局有多个资源文件夹吗?如果是的话,也许你没有相关的布局。