java - How to check if socket is connected or not using background thread -
i developing application in checking availability of port before reading , writing on socket. using following code check status
private boolean isavailable(string host, int port) { try { socket socket = new socket(); socket.connect(new inetsocketaddress(host, port), 1000); isportavailable = socket.isconnected(); } catch (ioexception e) { isportavailable = false; } return isportavailable; }
after checking status on onclick()
if (isavailable(ip, integer.parseint(portlvr))) { startactivity(new intent(getapplicationcontext(),activitylivingroom.class)); } else toast.maketext(getapplicationcontext(),"connection error !", toast.length_short).show();
but problem if check status on main thread android give me networkonmainthradexception
how manage operation using background thread?
try this
private class socketchecktask extends asynctask<string , integer , boolean> { string classname=""; public socketchecktask (string classname) { this.classname=classname; } @override protected boolean doinbackground(string... params) { return isavailable(params[0], integer.parseint(params[1]); } @override protected void onpostexecute(boolean isavailable) { if (isavailable)) { class c=class.forname("yourpackage"+classname); startactivity(new intent(getapplicationcontext(),c)); } else toast.maketext(getapplicationcontext(),"connection error !", toast.length_short).show(); } }
and send this
socketchecktask task=new socketchecktask ("activitylivingroom"); task.execute(ipadress,port);
Comments
Post a Comment