0

I want to check whether Internet connection is turned on or not when app starts. It should allow to start if internet is connected. Else display a error message and direct user to settings. Message need to be displayed until Internet connection is turned on.

Already I finished connection check function and alert display function. How could I listen whether internet is turned on or not after user directed to settings

connection check function is,

public boolean connectionIsAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        return true;
    }
    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
        return true;
    }
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        return true;
    }
    return false;
}

and alert display,

public void displayAlertDialog(final Context context){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL);
    alertDialogBuilder.setMessage("Would you like to enable it?")
            .setTitle("No Internet Connection")
            .setPositiveButton(" Enable Internet ", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(dialogIntent);
                }
            });

    alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int id){
            dialog.cancel();
        }
    });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

In my onCreate I check like,

if(connectionIsAvailable(getApplicationContext())) {
    welcomeThread.start();
} else {
    displayAlertDialog(LoadingScreenActivity.this);
}

Help me how could I listen whether internet is turned on or not after user directed to settings. Thanks in advance.

Kavin-K
  • 1,948
  • 3
  • 17
  • 48
  • Have you tried a [BroadcastReceiver](https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app)? – Sam Jan 23 '18 at 02:51

4 Answers4

0

When phone's network status changed, it will send a broadcast. So you just need a BroadcastReceiver.

For more detail check official documentation

Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
leimenghao
  • 226
  • 1
  • 10
0

You have to use BroadcasrReceive

try this.

Create class for BroadcastReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
      //Do your code 
    }
}

and register it in manifest file like this

<receiver android:name=".NetworkChangeReceiver" >
       <intent-filter>
             <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
       </intent-filter>
</receiver>
Mayank Panchal
  • 355
  • 1
  • 10
0

Manifest:

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

<!--Custom Broadcast Receiver for checking Internet Connectivity-->
        <receiver
            android:name=".extras.ConnectivityReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        <!--End-->

Connectivity Receiver Class:

public class ConnectivityReceiver extends BroadcastReceiver {

    public static ConnectivityReceiverListener connectivityReceiverListener;

    public ConnectivityReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent arg1) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null
                && activeNetwork.isConnectedOrConnecting();

        if (connectivityReceiverListener != null) {
            connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
        }
    }

    /**
     * Checking if internet connection is active or not
     * @return
     */
    public static boolean isConnected() {
        ConnectivityManager
                cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null
                && activeNetwork.isConnectedOrConnecting();
    }


    public interface ConnectivityReceiverListener {
        void onNetworkConnectionChanged(boolean isConnected);
    }
}

Activity Code:

public class HomeActivity extends AppCompatActivity
        implements ConnectivityReceiver.ConnectivityReceiverListener {



/**
     * Callback will be triggered when there is change in
     * network connection
     */
    @Override
    public void onNetworkConnectionChanged(boolean isConnected) {
        if (!isConnected) {
            // show dialog \\
        } else {
            // check if dialog is visible \\
           // if visible then dismiss else do your stuff \\
        }

    }


@Override
    protected void onResume() {
        super.onResume();
        // Register connection status listener \\
        MyApplication.getInstance().setConnectivityListener(this);
    }

}

My Application class code and set it in manifest:

public class MyApplication extends Application {

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    //-------Broadcast Receiver for Checking Internet Connection----------\\
    public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;
    }
    //----------------------------------------------------------------------\\

}
Rahul Singh Chandrabhan
  • 2,531
  • 5
  • 22
  • 33
0

Register receiver in manifest file

<!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
<receiver
            android:name=".InternetConnectorReceiver"
            android:enabled="true">
            <intent-filter>

                <!-- Intent filters for broadcast receiver -->
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                <action android:name="android.net.wifi.STATE_CHANGE" />
            </intent-filter>
</receiver>
Required permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

InternetConnectorReceiver.class

public class InternetConnectorReceiver extends BroadcastReceiver {

    // you can perform the action based on InternetConnected or not based on value of this variable.
  public static boolean IsInternetConnected = true;

    public InternetConnectorBroadcastReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            boolean isVisible = NameOfapplicationclass.isActivityVisible();
            // If it is visible then trigger the task else do nothing
            if (isVisible == true) {
                if (isInternetConnected(context)) {
                    IsInternetConnected = true;
                }
                else
                {
                    IsInternetConnected = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

public static boolean isInternetConnected(Context context) {
        ConnectivityManager cmObj = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cmObj.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            return true;
        }
        return false;
    }

Add Following code in application class

public static boolean activityVisible;

    public static boolean isActivityVisible() {
        return activityVisible; // return true or false
    }

    public static void activityResumed() {
        activityVisible = true;// this will set true when activity resumed

    }

    public static void activityPaused() {
        activityVisible = false;// this will set false when activity paused

    }
jessica
  • 1,700
  • 1
  • 11
  • 17