简体   繁体   中英

How to detect internet Connectivity on hotspot network in android

Me and my friends together have build an android app which requires internet connectivity to run. This is our first app and we just beginners and very much thanks to stack overflow. It helped us a lot.

So I used the code below to detect the connectivity

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null)
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
  }
}

And used the method in the splash activity as follows :

cd = new ConnectionDetector(getApplicationContext());

            if (cd.isConnectingToInternet()) {
                Intent intent = new Intent(SplashActivity.this, Home.class);
                SplashActivity.this.startActivity(intent);
                SplashActivity.this.finish();
            } else {
                Toast.makeText(SplashActivity.this, "No Internet Connection. Press back to exit", Toast.LENGTH_SHORT).show();
                finish();
            }

So the problem is when the mobile is connected to mobile data it works fine but when it is connected to a hotspot network, it only detects the network connectivity not the internet.

So the methods returns true and it goes to the next activity and the app crashes.

Is there any way to solve this?

I just want that my app shouldn't crash.

may be this will help you out.

  public boolean isInternetConnected(Context context) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService
                    (Context
                            .CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM