1

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

  • `if (NetworkCheck.IsReachable(SplashsActivity.this)){` is the error. – SRB Bans Jan 21 '17 at 11:54
  • 1
    Possible duplicate of [How to fix android.os.NetworkOnMainThreadException?](http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception) – Noorul Jan 21 '17 at 12:12
  • Move all your `NetworkCheck` calls into `doInBackground()` of your `DownloadLatestData` task. – CommonsWare Jan 21 '17 at 12:24
  • @CommonsWare and if server is not available...its keeping progress dialogue always....How to put condition in it ? – Anisha Pandey Jan 21 '17 at 14:02

2 Answers2

1

you don't need to check if URL is reachable or not, just call your new DownloadLatestData().execute(); if network available.

and put the condition in your asynctask if failed or success.

SRB Bans
  • 3,096
  • 1
  • 10
  • 21
0

You should make all network call in a separate background thread. Android has a strict rule on not allowing any network call on main thread. Try implementing your IsReachable(Context context) method inside separate thread using class like AsyncTask.

Edit You can try like this

public class Connection extends AsyncTask<Void, Void, Boolean> {

    private ConnectivityManager mConnectivityManager;
    private OnConnectionEstablishedListener mListener;

    public interface OnConnectionEstablishedListener {
        void onConnectionEstablished(boolean isReachable);
    }

    public Connection(ConnectivityManager connectivityManager, OnConnectionEstablishedListener listener) {
        mConnectivityManager = connectivityManager;
        mListener = listener;
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        final NetworkInfo netInfo = mConnectivityManager.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;
    }

    @Override
    protected void onPostExecute(Boolean isReachable) {
        super.onPostExecute(isReachable);
        mListener.onConnectionEstablished(isReachable);
    }
}

And your calling Activity should implement OnConnectionEstablishedListener like this

@Override
public void onConnectionEstablished(boolean isConnected) {
    new DownloadLatestData().execute();
} 

Suggestion: Although this all can be achieved in your DownloadLatestData with proper implementation.

Hussain
  • 1,243
  • 12
  • 21
  • can you give me example of it that How can I use it ? – Anisha Pandey Jan 21 '17 at 11:59
  • Thanks a lot for nice coding and example. I have made connection class. But now confuse in how to use this with my servercall method . You can check how I was using it. Can You please tell me how can I use it with ServerCall ? Thanks – Anisha Pandey Jan 21 '17 at 13:52