I am checking internet on splash activity and if internet available I am checking server is online or not with below method
private void serverCall() {
database = DAO.getInstance(getApplicationContext()); //added by eagleeyes
pref = new Setting_preference(this);
if (!mIsBackButtonPressed) {
pref.editor.putBoolean("sound", true);
pref.editor.putBoolean("vibrate", true);
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
if (NetworkCheck.IsReachable(SplashsActivity.this)){
new DownloadLatestData().execute();
}
else {
if (database.isDataBaseCreated()) {
Intent i = new Intent(SplashsActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
} else {
connectionerror();
}
}
} else {
if (database.isDataBaseCreated()) {
Intent i = new Intent(SplashsActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
} else {
connectionerror();
}
}
}
}
I am getting error that
java.lang.RuntimeException:android.os.NetworkOnMainThreadException
Because of server check on Main Thread. I have thought lot of option but I have not got any perfect idea for solve it. My server checking code is like below
public static boolean IsReachable(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
boolean isReachable = false;
if (netInfo != null && netInfo.isConnected()) {
// Some sort of connection is open, check if server is reachable
try {
URL url = new URL(DataManager.SIMPLE_BASE_URL);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10 * 2000);
urlc.connect();
isReachable = (urlc.getResponseCode() == 200);
} catch (IOException e) {
//Log.e(TAG, e.getMessage());
}
}
return isReachable;
}
What should I do for solve this issue ?
If I use StrictMode policy with below code then its working fine...But I am confuse that I can use it or not.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Let me know someone can help me for come out from this issue. Thanks