我正在尝试创建一个简单的Android应用程序,通过WiFi将字符串发送到微控制器,稍后将其用作打开和关闭LED的命令。
以下是我所拥有的代码,我遇到的问题是理解为什么它不起作用。 基本上抛出了一个异常,并且“连接失败”toast被占用。
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();
}
}
});
}
}
答案 0 :(得分:0)
不应该只是举杯,而应该使用
Log.d(getClass().getSimpleName(), "Connection failed", exception);
您可能遇到的问题是您在主线程上运行网络连接,这会在超时时冻结应用程序,因此Android操作系统不允许这样做。
查看此问题,了解有关如何在其他线程上运行网络连接的更多信息,并解决您的问题:Using AsyncTask for android network connection