-2

I need to know how to check if the device is connected to a network.

  1. If it is connected, user should be able to login.
  2. If not, user should get an error message telling that:

connect to a network first before logging in...

Below are my codes:

login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                username = user.getText().toString();
                password = pass.getText().toString();
                DatabaseOperations dop = new DatabaseOperations(ctx);
                Cursor cr = dop.getInformation(dop);
                cr.moveToFirst();
                boolean loginstatus=false;
                String Name= "";
                do
                {
                    if(username.equals(cr.getString(2))&& (password.equals(cr.getString(3))))
                    {
                        loginstatus=true;
                        Name = cr.getString(0);
                    }


                }while(cr.moveToNext());
                if(loginstatus)
                {
                    Toast.makeText(ctx, "Welcome \n" + Name, Toast.LENGTH_LONG).show();
                    Intent i = new Intent(ctx, MainActivity.class);
                    startActivity(i);
                    finish();
                }else
                {
                    Toast.makeText(ctx, "Check your Credentials..", Toast.LENGTH_LONG).show();
                }
                }

        });
sooon
  • 4,718
  • 8
  • 63
  • 116
  • 2
    Your question is Duplicate :(http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out) – Mouad Abdelghafour AitAli Apr 20 '17 at 00:41
  • Possible duplicate of [How to check internet access on Android? InetAddress never times out](http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out) – Linh Apr 20 '17 at 01:14

2 Answers2

1

Create a broadcast receiver to receive network events from the OS:

public class ConnectivityReceiver extends BroadcastReceiver {
    private boolean isConnected = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            isConnected = activeNetwork != null &&
                    activeNetwork.isAvailable();

            if (isConnected) {
                onConnectionRestored();
            } else {
                onConnectionInterrupted();
            }
        }
    }

    private void onConnectionRestored() { //implement me }
    private void onConnectionInterrupted() { //implement me }

}

Then register it on the onStart() method of your activity/fragment/presenter to start listening:

connectivityReceiver = new ConnectivityReceiver();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityReceiver, intentFilter);

Don't forget to unregister when you are done:

@Override
protected void onStop() {
    unregisterReceiver(connectivityReceiver);
    super.onStop();
}
frankelot
  • 13,666
  • 16
  • 54
  • 89
  • The method getApplicationContext() is undefined for the type ConnectivityReceiver isConnected cannot be resolved to a variable The method onConnectionRestored() is undefined for the type ConnectivityReceiver why am i getting this errors?? i cant seem to find the problem – kim gonzales Apr 20 '17 at 00:58
  • replace `getApplicationContext()` with just `context`. Edited my answer – frankelot Apr 20 '17 at 00:59
  • how about the isConnected cannot be resolved to a variable The method onConnectionRestored() is undefined for the type ConnectivityReceiver errors? – kim gonzales Apr 20 '17 at 01:02
  • isConnected is just a boolean declared globally, onConnectionRestored and onConnectionInterrupted are methods you should implement and depend on your specific use case – frankelot Apr 20 '17 at 01:07
0

You can use broadcastreceiver to check Internet is connected or not like below.

MainActivity.Java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static TextView internetStatus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        internetStatus = (TextView) findViewById(R.id.internet_status);

        // At activity startup we manually check the internet status and change
        // the text status
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            changeTextStatus(true);
        } else {
            changeTextStatus(false);
        }
    }
    // Method to change the text status
    public void changeTextStatus(boolean isConnected) {

        // Change status according to boolean value
        if (isConnected) {
            internetStatus.setText("Internet Connected.");
            internetStatus.setTextColor(Color.parseColor("#00ff00"));
        } else {
            internetStatus.setText("Internet Disconnected.");
            internetStatus.setTextColor(Color.parseColor("#ff0000"));
        }
    }

    @Override
    protected void onPause() {

        super.onPause();
        MyApplication.activityPaused();// On Pause notify the Application
    }

    @Override
    protected void onResume() {

        super.onResume();
        MyApplication.activityResumed();// On Resume notify the Application
    }
}

Receiver.Java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Created by root on 7/4/17.
 */
public class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {

            boolean isVisible = MyApplication.isActivityVisible();// Check if
            // activity
            // is
            // visible
            // or not
            Log.i("ActivityVisible ", "visible : " + isVisible);

            // If it is visible then trigger the task else do nothing
            if (isVisible == true) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager
                        .getActiveNetworkInfo();

                // Check internet connection and accrding to state change the
                // text of activity by calling method
                if (networkInfo != null && networkInfo.isConnected()) {

                    new MainActivity().changeTextStatus(true);
                    Log.i("ActivityVisible ", "visible : " + isVisible);
                } else {
                    new MainActivity().changeTextStatus(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

MyApplication.Java

public class MyApplication  extends Application {
    // Gloabl declaration of variable to use in whole app

    public static boolean activityVisible; // Variable that will check the
    // current activity state

    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

    }

}

Manifest.Java

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theme.broadcastreceiver">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- This permissions are neccessary for broadcast receiver -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".Receiver"
            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>
    </application>

</manifest>
pradeep
  • 307
  • 1
  • 8