我知道这似乎是一个重复的问题,但实际上并非如此。我想通过套接字与一些传感器通信。连接在模拟器上工作正常,但是当我将它上传到 Android 设备上时它不会工作。调试后,我将我的应用程序缩小到使用以下代码简单地打开一个套接字。
try
{
Socket socket = new Socket(InetAddress.getByName(ipAddress).getHostAddress(), 10001);
}
catch (Exception e)
{
Toast.makeText(context, "Error: "+e.getMessage(), duration).show();
}
我只是打开一个套接字。这在模拟器上运行良好,但是当我在设备上运行这个应用程序时,它会挂起一段时间,甚至没有显示任何异常消息......任何想法可能是什么问题。(最初是 StrictMode 问题,但我解决了)。LogCat 上没有错误。我已经安装了android终端模拟器并尝试ping,回复很好。提前致谢
这是代码
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
Button btn;
private CharSequence text = "";
private Socket s;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View view){
//detect the view that was "clicked"
switch(view.getId())
{
case R.id.button1:
new LongOperation().execute("");
break;
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
s = new Socket(InetAddress.getByName("o2215.airq.org").getHostAddress(), 10001);
text = "Connection Made";
} catch (Exception e) {
text = "Error : ";
for(int i=0;i<e.getStackTrace().length;i++)
{
text = text +"\n"+ e.getStackTrace()[i];
}
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(text);
}
}
}
这在模拟器上可以正常工作,但在设备上却不行。