如何检查网络可用性或检查网络并打开移动网络?

时间:2014-07-15 09:10:08

标签: java android

作为初学者,我正在尝试开发一个Android应用程序,它从服务器数据库中获取数据。

此处,如果 Wi-Fi 不适用,我需要启用 3G - 或 2G - 数据,自动在Android设备上提供,或通过对话框打开移动网络。

6 个答案:

答案 0 :(得分:1)

如何检查WIFI互联网连接:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

在清单中添加权限:

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

如何检查移动互联网连接(3G / LTE):

boolean is3g = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .isConnectedOrConnecting();

// Checks if Mobile network is available ...

if(!is3g){

// IF MOBILE CONNECTION NOT AVAILBLE, OPEN SYSTEM SETTINGS FOR MOBILE NETWORKS

   Intent intent = new Intent();
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   intent.setAction(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
   startActivity(intent);

}

希望这有帮助,如果它适合你,请将其标记为已接受的答案。

答案 1 :(得分:0)

您可以通过此课程检查网络是否可用

 public class ConnectionDetector {

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

/**
 * Checking for all possible Internet providers
 * **/
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;
}

}

检查互联网

  ConnectionDetector conn = new ConnectionDetector(youractivity.this);
    if(conn.isConnectingToInternet()){
        // call network operations
    }else{
        // Toast
    }

希望这可以帮助你

答案 2 :(得分:0)

使用此代码检查网络的可用性: -

public class CheckConnection {

私有Context _context;

public CheckConnection(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;
}

}

答案 3 :(得分:0)

试试这个:

findViewById(R.id.button).setOnClickListener(
                        new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // Check for n/w connection
                                if (!NetworkService
                                        .isNetWorkAvailable(CurrentActivity.this)) {
                                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                            CurrentActivity.this);
                                    // set title
                                    alertDialogBuilder.setTitle("Warning");
                                    alertDialogBuilder
                                            .setMessage("Check your network connection and try again.");
                                    // set dialog message
                                    alertDialogBuilder
                                            .setCancelable(false)
                                            .setNegativeButton(
                                                    "Ok",
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(
                                                                DialogInterface dialog,
                                                                int id) {
                                                        }
                                                    });
                                    // create alert dialog
                                    AlertDialog alertDialog = alertDialogBuilder.create();

                                    // show it
                                    alertDialog.show();
                                } else {
                              // Do your action if network exists
                                    Intent i = new Intent(getApplicationContext(),NextActivity.class);
                                    startActivity(i);
                                }
                            }
                        });

NetworkService.java:

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

public final class NetworkService {

    private NetworkService() {}

    public static boolean isNetWorkAvailable(final Context contextActivity) {
        ConnectivityManager conMgr = (ConnectivityManager) contextActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }
}

在清单中添加这些权限:

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

答案 4 :(得分:0)

检查网络是否可用或不使用以下代码块

private boolean isNetworkAvailable(Context mContext) {
    // TODO Check network connection
    ConnectivityManager connMgr = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected())
        return true;
    else
        return false;
}
如果WIFI不可用,

接下来检查条件: -

private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);

setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);

} 你还需要这个

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

答案 5 :(得分:0)

// Checking for all possible internet providers
public boolean isConnectingToInternet(){

    ConnectivityManager connectivity = 
                         (ConnectivityManager) 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;
}

同时指定这些权限:

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