【问题标题】:Checking if there's an internet connection before executing code在执行代码之前检查是否有互联网连接
【发布时间】:2013-11-12 11:31:36
【问题描述】:

我想知道在执行我的一些代码之前是否有一种简单的方法可以检查用户是否有可用的互联网连接。

我想知道这一点,因为如果我不启用我的互联网连接然后单击“Setwallpaper”,应用程序会因为“Nullpointerexception”而崩溃,因为没有任何东西可以执行。

在打开下载和设置壁纸的异步任务类之前,我如何检查用户是否启用了互联网连接?

代码:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.SetWallpaper:

//Do something here that checks if the user has connection so if they don't, it won't execute this code here.

        new SaveWallpaperAsync(getActivity()).execute(mImageUrl);

        break;

    case R.id.SaveWallpaper:

//Do something here that checks if the user has connection so if they don't, it won't execute this code here.

        new SetWallpaperAsync(getActivity()).execute(mImageUrl);

        break;
    }
    return super.onOptionsItemSelected(item);
} 

【问题讨论】:

标签: android


【解决方案1】:

您需要在 oncreate() 或 onStart() 中编写以下代码

    CheckConnection ch = new CheckConnection();
    boolean status = ch.isNetworkAvailable(getApplicationContext());

    if (status) {

        //do Async task





    } else {
        // show error
    }


       public class CheckConnection {

    public boolean isNetworkAvailable(Context context) {            
        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;
    }

}

【讨论】:

    【解决方案2】:

    使用这个方法

    public static boolean checkInternetConnection(Context context)
    {
        try
        {
            ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
            // ARE WE CONNECTED TO THE NET
    
            if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    
        return false;
    }
    

    并添加权限

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

    在您的清单文件中

    【讨论】:

      【解决方案3】:

      尝试如下:

      public static boolean IsNetConnected() {
          boolean NetConnected = false;
      
          try {
              ConnectivityManager connectivity = (ConnectivityManager) m_context
                      .getSystemService(m_context.CONNECTIVITY_SERVICE);
      
              if (connectivity == null) {
                  NetConnected = false;
              } else {
                  NetworkInfo[] info = connectivity.getAllNetworkInfo();
      
                  if (info != null) {
                      for (int i = 0; i < info.length; i++) {
                          if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                              NetConnected = true;
                          }
                      }
                  }
              }
          } catch (Exception e) {
              e.printStackTrace();
              NetConnected = false;
          }
      
          return NetConnected;
      }
      

      并在清单中添加权限。

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

      在您的代码中执行以下操作:

      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
      
          case R.id.SetWallpaper:
      
      //Do something here that checks if the user has connection so if they don't, it won't execute this code here.
              if( IsNetConnected())
              {
                  new SaveWallpaperAsync(getActivity()).execute(mImageUrl);
               }
              break;
      
          case R.id.SaveWallpaper:
      
      //Do something here that checks if the user has connection so if they don't, it won't execute this code here.
              if( IsNetConnected())
              {
                  new SetWallpaperAsync(getActivity()).execute(mImageUrl);
                }
              break;
          }
          return super.onOptionsItemSelected(item);
      } 
      

      【讨论】:

      • m_context 是什么?它说“m_context 无法解析为变量”
      • 它是您使用此方法的活动的上下文。你可以通过thisyouractivityname.this
      • 顺便说一句,我的类是一个片段,当我使用我的类名 .this 时,我收到错误“不能在静态上下文中使用它”
      • 如果它的片段那么你需要像YouFragmentName.this.getActivity();一样写它
      • 嗯,我仍然收到错误“无法在静态上下文中使用它”
      【解决方案4】:

      我就是这样做的。在您要检查互联网连接的活动中将以下代码写入onCreate()

              NetworkConnectivity.sharedNetworkConnectivity().configure(this); 
              NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor(); 
              NetworkConnectivity.sharedNetworkConnectivity() 
                      .addNetworkMonitorListener(new NetworkMonitorListener() { 
                          @Override
                          public void connectionCheckInProgress() { 
                              // Okay to make UI updates (check-in-progress is rare) 
                          } 
      
                          @Override
                          public void connectionEstablished() { 
                              // Okay to make UI updates -- do something now that 
                              // connection is avaialble 
      
      
                          } 
      
                          @Override
                          public void connectionLost() { 
                              // Okay to make UI updates -- bummer, no connection 
      
                              Toast.makeText(getBaseContext(), "Connection lost. You cannot use Voice Input method.", Toast.LENGTH_LONG).show(); 
      
      
                          } 
                      }); 
      

      创建两个java文件:

      NetworkConnectivity.java

      package com.connectivity; 
      
      import java.util.ArrayList; 
      import java.util.List; 
      
      import android.app.Activity; 
      import android.content.Context; 
      import android.net.ConnectivityManager; 
      import android.net.NetworkInfo; 
      import android.os.Handler; 
      
      public class NetworkConnectivity { 
      
          private static NetworkConnectivity sharedNetworkConnectivity = null; 
      
          private Activity activity = null; 
      
          private final Handler handler = new Handler(); 
          private Runnable runnable = null; 
      
          private boolean stopRequested = false; 
          private boolean monitorStarted = false; 
      
          private static final int NETWORK_CONNECTION_YES = 1; 
          private static final int NETWORK_CONNECTION_NO = -1; 
          private static final int NETWORK_CONNECTION_UKNOWN = 0; 
      
          private int connected = NETWORK_CONNECTION_UKNOWN; 
      
          public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000; 
          public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000; 
      
          private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>(); 
      
          private NetworkConnectivity() { 
          } 
      
          public synchronized static NetworkConnectivity sharedNetworkConnectivity() { 
              if (sharedNetworkConnectivity == null) { 
                  sharedNetworkConnectivity = new NetworkConnectivity(); 
              } 
      
              return sharedNetworkConnectivity; 
          } 
      
          public void configure(Activity activity) { 
              this.activity = activity; 
          } 
      
          public synchronized boolean startNetworkMonitor() { 
              if (this.activity == null) { 
                  return false; 
              } 
      
              if (monitorStarted) { 
                  return true; 
              } 
      
              stopRequested = false; 
              monitorStarted = true; 
      
              (new Thread(new Runnable() { 
                  @Override
                  public void run() { 
                      doCheckConnection(); 
                  } 
              })).start(); 
      
              return true; 
          } 
      
          public synchronized void stopNetworkMonitor() { 
              stopRequested = true; 
              monitorStarted = false; 
          } 
      
          public void addNetworkMonitorListener(NetworkMonitorListener l) { 
              this.networkMonitorListeners.add(l); 
              this.notifyNetworkMonitorListener(l); 
          } 
      
          public boolean removeNetworkMonitorListener(NetworkMonitorListener l) { 
              return this.networkMonitorListeners.remove(l); 
          } 
      
          private void doCheckConnection() { 
      
              if (stopRequested) { 
                  runnable = null; 
                  return; 
              } 
      
              final boolean connectedBool = this.isConnected(); 
              final int _connected = (connectedBool ? NETWORK_CONNECTION_YES 
                      : NETWORK_CONNECTION_NO); 
      
              if (this.connected != _connected) { 
      
                  this.connected = _connected; 
      
                  activity.runOnUiThread(new Runnable() { 
                      @Override
                      public void run() { 
                          notifyNetworkMonitorListeners(); 
                      } 
                  }); 
              } 
      
              runnable = new Runnable() { 
                  @Override
                  public void run() { 
                      doCheckConnection(); 
                  } 
              }; 
      
              handler.postDelayed(runnable, 
                      (connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS 
                              : MONITOR_RATE_WHEN_DISCONNECTED_MS)); 
          } 
      
          public boolean isConnected() { 
              try { 
                  ConnectivityManager cm = (ConnectivityManager) activity 
                          .getSystemService(Context.CONNECTIVITY_SERVICE); 
                  NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
      
                  if (netInfo != null && netInfo.isConnected()) { 
                      return true; 
                  } else { 
                      return false; 
                  } 
              } catch (Exception e) { 
                  return false; 
              } 
          } 
      
          private void notifyNetworkMonitorListener(NetworkMonitorListener l) { 
              try { 
                  if (this.connected == NETWORK_CONNECTION_YES) { 
                      l.connectionEstablished(); 
                  } else if (this.connected == NETWORK_CONNECTION_NO) { 
                      l.connectionLost(); 
                  } else { 
                      l.connectionCheckInProgress(); 
                  } 
              } catch (Exception e) { 
              } 
          } 
      
          private void notifyNetworkMonitorListeners() { 
              for (NetworkMonitorListener l : this.networkMonitorListeners) { 
                  this.notifyNetworkMonitorListener(l); 
              } 
          } 
      
      } 
      

      NetworkMonitorListener.java

      package com.connectivity; 
      
      public interface NetworkMonitorListener { 
      
          public void connectionEstablished(); 
          public void connectionLost(); 
          public void connectionCheckInProgress(); 
      } 
      

      最后,在manifest.xml 中添加这两行:

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

      【讨论】:

        【解决方案5】:
            public static boolean isInternetAvailable(Context ctx) {
                    ConnectivityManager cm = (ConnectivityManager) ctx
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    if (netInfo != null && netInfo.isConnectedOrConnecting()
                            && cm.getActiveNetworkInfo().isAvailable()
                            && cm.getActiveNetworkInfo().isConnected()) {
                        return true;
                    } else {
                        return false;
                    }
                }
        public static void showNetworkAlertDialog(Context mCtx) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
            builder.setCancelable(false);
            builder.setTitle("Network Error");
            builder.setMessage("Internet is not available !!");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
        

        //比

           if(isInternetAvailable){
            // Execute code here
            }else{
           NetworkUtils.showNetworkAlertDialog(mContext);
            }
        

        //清单中的权限

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-30
          • 1970-01-01
          • 2019-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多