检测我的设备是否有互联网

Igo*_*gor 2 networking android

我希望我的应用程序能够检测我的设备是否有互联网连接.我写了这段代码,但它不起作用.这是代码:

package mi.internet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class navegando extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        comprobar();
    }

    private void comprobar() {
        Context context = null;
        // TODO Auto-generated method stub
        if(navegando.isOnline(context)== false) {
            new AlertDialog.Builder(this).setTitle("Advertencia").setMessage("No hay internet").setNeutralButton("Close", null).show();
           finish();
        }
    }
public static boolean isOnline(Context ctx) {
    ConnectivityManager connectivity = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) 
    {
        NetworkInfo[] network_info = connectivity.getAllNetworkInfo();
        if (network_info != null)
            for (int i = 0; i < network_info.length; i++)
                if (network_info[i].getState() == NetworkInfo.State.CONNECTED)
                    return true;
    }

    return false;
}
}
Run Code Online (Sandbox Code Playgroud)

谢谢!


谢谢你的所有答案.我是新手,我不知道如何使用此代码.当我的应用程序启动时,我希望如果没有互联网连接,屏幕上会显示一条消息,表示没有互联网连接并完成活动.

坦克你了!

Chi*_*rag 6

请尝试下面的代码.它检查设备中是否存在Internet连接.

public boolean CheckInternet() 
{
    ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    // Here if condition check for wifi and mobile network is available or not.
    // If anyone of them is available or connected then it will return true, otherwise false;

    if (wifi.isConnected() || mobile.isConnected()) {
        return true;
    } 
    return false;
}
Run Code Online (Sandbox Code Playgroud)

请在android清单文件中添加以下权限.

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <uses-permission android:name="android.permission.INTERNET" /> 
Run Code Online (Sandbox Code Playgroud)

  • +1,但是我很想把if/else语句放到一行中以使它超级性感;) (2认同)