如何编写 Android 互联网连接代码?

How to write Android code for internet connection?

如何使用互联网连接构建应用程序?

如果没有互联网,它必须显示一个警告框

MainActivity.java

     public class MainActivity extends AppCompatActivity {
    ConnectivityManager connectivityManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        String macadd = wifiManager.getConnectionInfo().getMacAddress();
        BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
        if (!BA.isEnabled()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("PLEASE READ THE FOLLOWING");
            builder.setMessage("Please On Your Bluetooth");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();

                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.setCancelable(false);
            alertDialog.show();
        }
 }

创建classNetworkInformation.java

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

    public class NetworkInformation {

         private static NetworkInfo networkInfo;

         public static boolean isConnected(Context context) {

                 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

                 try{
                    networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // test for connection for WIFI
                if (networkInfo != null
                        && networkInfo.isAvailable()
                        && networkInfo.isConnected()) {
                    return true;
                }

                networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                // test for connection for Mobile
                if (networkInfo != null
                        && networkInfo.isAvailable()
                        && networkInfo.isConnected()) {
                    return true;
                }

                return false;
          }   

    }

现在在调用网络相关任务(异步任务)之前检查网络是否可用,如下所示:

if(NetworkInformation.isConnected(YourClassName.this))
        {
             new FetchWebsiteData().execute();        
        }else{

        Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show();
        }

不要忘记在 AndroidManifest.xml 中包含以下权限:

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

ManifestPermssions:

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

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

检查 android 目标 android 6.0 及更高版本的运行时权限。

public class MainActivity extends AppCompatActivity {
    Context context;
    private static final int REQUEST_RUNTIME_PERMISSION = 123;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        if (CheckPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE)) {
            // you have permission go ahead
            checkIntetnetConnection();
        } else {
            // you do not have permission go request runtime permissions
            RequestPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE, REQUEST_RUNTIME_PERMISSION);
        }

    }

    private void checkIntetnetConnection() {
        if (isNetworkAvailable()) {
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("PLEASE READ THE FOLLOWING");
            builder.setMessage("Please On Your Bluetooth");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();

                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.setCancelable(false);
            alertDialog.show();
        }
    }

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

    @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
        switch (permsRequestCode) {

            case REQUEST_RUNTIME_PERMISSION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // you have permission go ahead
                    checkIntetnetConnection();
                } else {
                    // you do not have permission show toast.
                }
                return;
            }
        }
    }

    public void RequestPermission(Activity thisActivity, String Permission, int Code) {
        if (ContextCompat.checkSelfPermission(thisActivity,
                Permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Permission)) {
            } else {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Permission},
                        Code);
            }
        }
    }

    public boolean CheckPermission(Context context, String Permission) {
        if (ContextCompat.checkSelfPermission(context,
                Permission) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }
}

新建javaclass.....

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

 public class Connectionstatus {
   private static Connectionstatus instance = new Connectionstatus();
   static Context context;
   ConnectivityManager connectivityManager;
   NetworkInfo wifiInfo, mobileInfo;
   boolean connected = false;

   public static Connectionstatus 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;
 }

}

在你的 Activity...

if (Connectionstatus.getInstance(this).isOnline())
    {
        Toast.makeText(this,"Your Internet Connection is Working...",Toast.LENGTH_LONG).show();
else
    {
        Toast.makeText(this,"Your Internet Connection is not working,\nPlease Check Internet Connection...!!!",Toast.LENGTH_LONG).show();
    }

清单文件:

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
  public class InternetConnectionBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {


        //Do your operation you will get here on connectivity change

        if (isOnline()) {

        //show dialog

        } else {

       //dismiss dialog

        }

    }

}



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;

}

在您的 activity 中注册此接收器:

registerReceiver(internetConnectionBroadcast, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

下面是在android app

中检查网络连接的方法
public static Boolean checkNetworkConnection(Context context) {
    ConnectivityManager connectivityManager;
    try {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        if (activeNetwork != null) { // connected to the internet
            return true;
        }
    } catch (Exception exception) {
        Log.d(TAG, "CheckConnectivity Exception: " + exception.getMessage());
    }
    return false;
}