morha13 morha13 - 3 months ago 11
Android Question

Activity won't load when checking internet connection

I'm trying to create an app that checks for internet connection when it opens. I want it to display a loading screen as long as there is not internet connection and a message. The loading screen activity is

activity_main.xml
. The problem is that because I'm calling
LoggingIn
method from itself, it keeps repeating it untill I have internet connection, but the problem is that for some reason it just won't load the activity itself. It just shows me a blank screen. When I don't run LoggingIn the activity does work.

Please help is there any other way to do this?

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoggingIn();
}

public void LoggingIn ()
{
if (isNetworkAvailable())
{
if (findViewById(R.id.InternetConnection).getVisibility() == View.VISIBLE)
{
findViewById(R.id.InternetConnection).setVisibility(View.GONE);
}
AttemptLoggingIn();
}
else
{
findViewById(R.id.InternetConnection).setVisibility(View.VISIBLE);
LoggingIn();


}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Answer

Use background threads instead of your very strange method.

For example,

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startCheck();
}


    private boolean startCheck() {
        new Thread(new Runnable() {

                        @Override
                        public void run() {
        runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                          findViewById(R.id.InternetConnection).setVisibility(View.VISIBLE);
                    }
                });

        while(!isNetworkAvailable()) {

        try {
                                    Thread.sleep(100L);// 100 ms sleep
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
        }
        runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (findViewById(R.id.InternetConnection).getVisibility() == View.VISIBLE)
                {
                    findViewById(R.id.InternetConnection).setVisibility(View.GONE);
                }
                AttemptLoggingIn();
                    }
                });

        }
                    }).start();
    }