Development Tip

Android에서 사용할 수있는 인터넷 연결이 있는지 감지

yourdevel 2020. 9. 30. 11:37
반응형

Android에서 사용할 수있는 인터넷 연결이 있는지 감지 [중복]


Android 기기가 인터넷에 연결되어 있는지 감지해야합니다.

NetworkInfo클래스는 isAvailable()완벽하게 들리는 비 정적 메서드 제공합니다 .

문제는 다음과 같습니다.

NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
    // do something
}

이 오류가 발생합니다.

The constructor NetworkInfo is not visible.

안전한 방법은 NetworkInfo객체 를 반환하는 다른 클래스가 있다는 것입니다 . 그러나 나는 무엇을 모른다.

  1. 위의 코드 스 니펫을 작동시키는 방법은 무엇입니까?
  2. 온라인 문서에서 필요한 정보를 어떻게 찾을 수 있습니까?
  3. 이러한 유형의 탐지를위한 더 나은 방법을 제안 할 수 있습니까?

getActiveNetworkInfo()메서드 는 찾을 수있는 첫 번째 연결된 네트워크 인터페이스를 나타내는 인스턴스 ConnectivityManager반환 NetworkInfo하거나 null연결된 인터페이스가없는 경우 반환합니다 . 이 메서드가 반환되는지 확인하면 null인터넷 연결을 사용할 수 있는지 여부를 알 수 있습니다.

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

또한 다음이 필요합니다.

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

당신의 안드로이드 매니페스트에서.

편집하다:

활성 네트워크 인터페이스가 있다고해서 특정 네트워크 서비스를 사용할 수 있다는 보장은 없습니다. 네트워크 문제, 서버 다운 타임, 낮은 신호, 종속 포털, 콘텐츠 필터 등으로 인해 앱이 서버에 도달하지 못할 수 있습니다. 예를 들어 트위터 서비스에서 유효한 응답을받을 때까지 앱이 트위터에 도달 할 수 있는지 확실하게 알 수 없습니다.


다음과 같이 Wi-Fi와 모바일 인터넷을 모두 확인합니다.

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.


Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:

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


public class AppStatus {

    private static AppStatus instance = new AppStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();
        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...

if (AppStatus.getInstance(this).isOnline()) {

    Toast.makeText(this,"You are online!!!!",8000).show();

} else {

    Toast.makeText(this,"You are not online!!!!",8000).show();
    Log.v("Home", "############################You are not online!!!!");    
}

Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE in your AndroidManifest.xml for this to work.

_ how could I have found myself the information I needed in the online documentation?

You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.


The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

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

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.


Probably I have found myself:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();

참고URL : https://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android

반응형