【发布时间】:2014-07-22 07:42:13
【问题描述】:
我正在尝试制作一个简单的 Android 应用程序,通过 WiFi 将字符串发送到微控制器,该微控制器稍后将用作打开和关闭 LED 的命令。
以下是我拥有的代码,我在理解它为什么不起作用时遇到了问题。 基本上抛出异常并引发“连接失败”吐司。
String hostname = "192.168.50.1";
int port = 5001;
PrintWriter out = null;
//access_point.connect(new InetSocketAddress(hostname, port));
public void command() throws Exception {
try{
Socket access_point = new Socket(hostname,port);
out = new PrintWriter(access_point.getOutputStream(), true);
out.println("Turn on");
Toast.makeText(getBaseContext(), "Connection successful", Toast.LENGTH_LONG).show();
// BufferedReader in = new BufferedReader(new InputStreamReader(access_point.getInputStream()));
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Connection failed", Toast.LENGTH_LONG).show();
}
}
ToggleButton tbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
// code for toggle button
tbutton = (ToggleButton) findViewById(R.id.toggleButton1);
tbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(((ToggleButton)v).isChecked())
{
try{
command();
Toast.makeText(getBaseContext(), "Communication ON string sent", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), "Communication failed", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getBaseContext(), "Communication OFF string sent", Toast.LENGTH_LONG).show();
}
}
});
}
}
【问题讨论】:
-
记录您的异常以查看可能的
NetworkOnMainThreadException