我正在开发一个使用arduino + ethernet shield + android app来控制灯光的项目。我正在使用android studio进行应用程序开发。问题是,try-catch块已经在OnClickListener()中实现,它似乎不起作用。我是Android应用程序开发的新手,无法想到同样的解决方案。该应用程序已安装,但按钮不执行其功能。即服务器没有收到任何包。实际上,最初targetSdkVersion设置为8,因此holo主题和按钮工作正常。一旦我将它设置为22(棒棒糖),默认情况下应用材质主题,按钮不再起作用。提前感谢你。
public void led(String s) throws Exception
{
byte[] b=(s.getBytes());
if(isOnline())
{
serverHostname1 = new String ("192.168.1.177");
ip = InetAddress.getByName(serverHostname1);
d1 = new DatagramSocket();//}
try{
send = new DatagramPacket(b,b.length, ip, 8032);
}catch(Exception e){
}
d1.send(send);
d1.setSoTimeout(10000);
d1.receive(rec);
modifiedSentence = new String(rec.getData());
InetAddress returnIPAddress = rec.getAddress();
Toast.makeText(getApplicationContext(),"Reply from Server:"+returnIPAddress,Toast.LENGTH_LONG).show();
d1.close();
}
else
{
Toast.makeText(getApplicationContext(),"No network",Toast.LENGTH_LONG).show();
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button on= (Button)findViewById(R.id.on);
Button off= (Button)findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
//ArduinoActivity a=new ArduinoActivity();
led("1");
Toast.makeText(getApplicationContext(),"ON",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error::"+e);
}
}
});
off.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
//ArduinoActivity b=new ArduinoActivity();
led("2");
Toast.makeText(getApplicationContext(), "OFF",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
//TODO Auto-generated catch block
System.out.println("Error::"+e);
}
}
});
}
}
答案 0 :(得分:-1)
问题不在于try-catch块,而是在UI线程(发送数据包)内部执行的网络操作,这在Android 3.0版本中是不允许的。解决方案是使用Asynctask。谢谢:))