Android - Programmatically check internet connection and display dialog if notConnected

*爱你&永不变心* 提交于 2019-11-28 23:06:13

You could checkout this library:

https://github.com/novoda/merlin

You just implement Connectable and you will get a callback when the network goes down or comes up.

Therefore you can show your dialog in this scenario.

You can also query the library for the current state and choose not to do your network task

Create Merlin (using Merlin.Builder())

merlin = new Merlin.Builder().withConnectableCallbacks().build(context);

Bind and unbind the service in your activity

@Override
protected void onResume() {
    super.onResume();
    merlin.bind();
}

@Override
protected void onPause() {
    super.onPause();
    merlin.unbind();
}

Register for callbacks

merlin.registerConnectable(new Connectable() {
        @Override
        public void onConnect() {
            // Do something!
        }
});

The MerlinActivity within the demo shows a simple way to declutter Merlin from your main application code.

Java_Android

Finally, I got the answer.

ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
    Description.setVisibility(View.INVISIBLE);
    new AlertDialog.Builder(WelcomePage.this)
        .setTitle(getResources().getString(R.string.app_name))
        .setMessage(getResources().getString(R.string.internet_error))
        .setPositiveButton("OK", null).show();
}else{
    dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,false);
    new Welcome_Page().execute();
}

Check internet connection

 ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo netInfo = mgr.getActiveNetworkInfo();

        if (netInfo != null) {
            if (netInfo.isConnected()) {
                // Internet Available
            }else {
               //No internet
            }
        } else {
            //No internet
        }
putulputul

This is simple function that check your Internet connection. If Connected return true otherwise false.

 public boolean isInternetOn() {

        // get Connectivity Manager object to check connection
        ConnectivityManager connec =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {


            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {


            return false;
        }
        return false;
    }
}

Here's a project that check internet connection and also check url that valid or contain in sever this.

I've tried different methods described above, besides it I've been caught in some cases. So finally, I'm using below code snippet to make a network call...

try {
    InetAddress address = InetAddress.getByName("www.stackoverflow.com");
    //Connected to working internet connection
} catch (UnknownHostException e) {
    e.printStackTrace();
    //Internet not available
}

This can be useful in many perspectives. If something is not fine in this approach, please let me know.

if (InternetConnection.checkConnection(context)) {
    // Internet Available...
} else {
    // Internet Not Available...
}

just copy below class

public class InternetConnection {

    /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
    public static boolean checkConnection(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

        if (activeNetworkInfo != null) { // connected to the internet
            Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();

            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                return true;
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                return true;
            }
        }
        return false;
    }
}

Give following permission to manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

doInBackground runs on a different Thread than the main UI, so you can't create a show a dialog here. Instead, override onPreExecute in your AsyncTask, and do the test there.

Bipin Patel
 public boolean isOnline() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) 
        getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return activeNetworkInfo != null && 
        activeNetworkInfo.isConnectedOrConnecting();
    }

Internet connection also check either in onCreate() or onResume() method. There is no need to call inside the AsyncTask.

or You can call before call the AsyncTask execute() method

if(isOnline)
{
   MyAsyncTask task=new MyAMyAsyncTask();
   task.execute();

}

else
{
// no internet connection
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!