I am using XBMC android source code and now try to extract some code to new xbmc android project. When i try to connect to a ip address and check whether it is reachable using isReachable(), it is throwing a NetworkOnMainThreadException but same source code(in XBMC source code that is i downloded from the git) it is working fine, This is the source code i'm working on
Handler handler = new Handler(){
public void handleMessage(android.os.Message message){
if(message.getData().containsKey(MacAddressResolver.MESSAGE_MAC_ADDRESS)){
String mac = message.getData().getString(MacAddressResolver.MESSAGE_MAC_ADDRESS);
if(!mac.equals("")) {
mMacAddrView.setText(mac);
Toast toast = Toast.makeText(getContext(), "Updated MAC for host: " + mHostView.getText().toString() + "\nto: " + mac, Toast.LENGTH_SHORT);
toast.show();
}
}
}
};
public class MacAddressResolver implements Runnable{
private String mHost = null;
private String mMac = null;
private Handler mHandler;
public static final String MESSAGE_MAC_ADDRESS = "MAC_ADDRESS";
public MacAddressResolver(String ipString, Handler handler){
mHost = ipString;
mHandler = handler;
}
public void run(){
mMac = arpResolve(mHost);
Bundle bundle = new Bundle();
bundle.putString(MESSAGE_MAC_ADDRESS, mMac);
Message message = new Message();
message.setData(bundle);
mHandler.sendMessage(message);
}
private String arpResolve(String host){
System.out.println("ARPRESOLVE HOST: " + host);
try{
//Parse it as a proper InetAddress - it might be a hostname. We don't know yet.
InetAddress inet = InetAddress.getByName(host);
//initiate some sort of traffic to ensure we get an arp entry (if we're on same subnet, that is...)
inet.isReachable(500); //timeout of 500ms. just to trigger the arp resolution process
//Get the official string representation of the resolved ip address
String ipString = inet.getHostAddress();
BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
String line = "";
while(true){
line = br.readLine();
if (line == null)
break;
if(line.startsWith(ipString)){
br.close();
System.out.println("ARPRESOLVE MAC:\n" + line);
return line.split("\\s+")[3]; // 4th word, separated by "whitespace"
}
}
br.close();
return "";
}catch(Exception e){
return "";
}
}
}
and i also put these two permission in my AndroidManifest.xml file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="13" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I don't know, what is the problem and how can i fix it?
NetworkOnMainThreadException exception
means that you are doing some Networking Work
on MainThread
(which will overload that Thread
and throw an Exception
).
So, you have to move that Networking Code
to the Background Thread
(another thread
other then Main Thread
).
AsyncTask is a good example to handle such things