2014-11-04 122 views
0

正如我想问的标题状态,我如何继续检查设备是否具有互联网连接? 我用下面的类:继续检查设备是否具有互联网连接

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


public class checkConnection { 

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

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

但是一旦这个活动只检查开始后,如果该设备具有与否互联网连接,如果我想继续检查我怎么可以创建整个活动的循环?

回答

2
public class NetworkChangeReceiver extends BroadcastReceiver { 

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

if(checkInternet(context)) 
{ 
    Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
} 

} 


boolean checkInternet(Context context) { 
     ServiceManager serviceManager = new ServiceManager(context); 
     if (serviceManager.isNetworkAvailable()) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

} 

ServiceManager.java

public class ServiceManager extends ContextWrapper { 

public ServiceManager(Context base) { 
    super(base); 
} 

public boolean isNetworkAvailable() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     return true; 
    } 
    return false; 
} 

} 

权限:

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

而且不要忘记注册接收这样的主要活动 -

registerReceiver(mConnReceiver, 
      new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 
    } 
} 

参考。 here

1

只要连接更改 ,您就必须使用Brodcast Receiver注册列表程序,然后像这样检查互联网连接。


             
  
public class NetworkConnectivityListener { 
 
    \t private static final String TAG = "NetworkConnectivityListener"; 
 
    \t private static final boolean DBG = true; 
 

 
    \t private Context mContext; 
 
    \t private State mState; 
 
    \t private boolean mListening; 
 
    \t private String mReason; 
 
    \t private boolean mIsFailover; 
 
    \t boolean isWifiConnected = false; 
 
    \t boolean isMobileConnected = false; 
 
    \t private static NetworkConnectivityListener Networkobject; 
 
    \t private MainThreadBus mThreadBus; 
 
    \t public static NetworkConnectivityListener newInstance() { 
 
    \t \t if (Networkobject == null) { 
 
    \t \t \t Networkobject = new NetworkConnectivityListener(); 
 
    \t \t } 
 
    \t \t return Networkobject; 
 
    \t } 
 

 
    \t /** Network connectivity information */ 
 
    \t private NetworkInfo mNetworkInfo; 
 

 
    \t /** 
 
    \t * In case of a Disconnect, the connectivity manager may have already 
 
    \t * established, or may be attempting to establish, connectivity with another 
 
    \t * network. If so, {@code mOtherNetworkInfo} will be non-null. 
 
    \t */ 
 
    \t private NetworkInfo mOtherNetworkInfo; 
 

 
    \t private ConnectivityBroadcastReceiver mReceiver; 
 

 
    \t private class ConnectivityBroadcastReceiver extends BroadcastReceiver { 
 
    \t \t @SuppressWarnings("deprecation") 
 
    \t \t @Override 
 
    \t \t public void onReceive(Context context, Intent intent) { 
 
    \t \t \t String action = intent.getAction(); 
 

 
    \t \t \t if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION) 
 
    \t \t \t \t \t || mListening == false) { 
 
    \t \t \t \t Log.d(TAG, "onReceived() called with " + mState.toString() 
 
    \t \t \t \t \t \t + " and " + intent); 
 
    \t \t \t \t return; 
 
    \t \t \t } 
 

 
    \t \t \t ConnectivityManager connMgr = (ConnectivityManager) context 
 
    \t \t \t \t \t .getSystemService(Context.CONNECTIVITY_SERVICE); 
 

 
    \t \t \t NetworkInfo networkInfo = connMgr 
 
    \t \t \t \t \t .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
 

 
    \t \t \t if (networkInfo != null) 
 
    \t \t \t \t isWifiConnected = networkInfo.isConnected(); 
 

 
    \t \t \t networkInfo = connMgr 
 
    \t \t \t \t \t .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
 

 
    \t \t \t if (networkInfo != null) 
 
    \t \t \t \t isMobileConnected = networkInfo.isConnected(); 
 

 
    \t \t \t Log.d("network status", "wifi == " + isWifiConnected 
 
    \t \t \t \t \t + " and mobile == " + isMobileConnected); 
 

 
    \t \t \t boolean noConnectivity = intent.getBooleanExtra(
 
    \t \t \t \t \t ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); 
 

 
    \t \t \t if (noConnectivity) { 
 
    \t \t \t \t mState = State.NOT_CONNECTED; 
 
    \t \t \t } else { 
 
    \t \t \t \t mState = State.CONNECTED; 
 
    \t \t \t } 
 

 
    \t \t \t mNetworkInfo = (NetworkInfo) intent 
 
    \t \t \t \t \t .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); 
 
    \t \t \t mOtherNetworkInfo = (NetworkInfo) intent 
 
    \t \t \t \t \t .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); 
 

 
    \t \t \t mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); 
 
    \t \t \t mIsFailover = intent.getBooleanExtra(
 
    \t \t \t \t \t ConnectivityManager.EXTRA_IS_FAILOVER, false); 
 
    \t \t \t System.out.println("Printing the MYTest" + mNetworkInfo); 
 
    \t \t \t if (DBG) { 
 
    \t \t \t \t Log.d(TAG, 
 
    \t \t \t \t \t \t "onReceive(): mNetworkInfo=" 
 
    \t \t \t \t \t \t \t \t + mNetworkInfo 
 
    \t \t \t \t \t \t \t \t + " mOtherNetworkInfo = " 
 
    \t \t \t \t \t \t \t \t + (mOtherNetworkInfo == null ? "[none]" 
 
    \t \t \t \t \t \t \t \t \t \t : mOtherNetworkInfo + " noConn=" 
 
    \t \t \t \t \t \t \t \t \t \t \t \t + noConnectivity) + " mState=" 
 
    \t \t \t \t \t \t \t \t + mState.toString()); 
 
    \t \t \t } 
 

 
    \t \t \t mThreadBus.post(getState()); 
 
    \t \t } 
 
    \t }; 
 

 
    \t public enum State { 
 
    \t \t UNKNOWN, 
 

 
    \t \t /** This state is returned if there is connectivity to any network **/ 
 
    \t \t CONNECTED, 
 
    \t \t /** 
 
    \t \t * This state is returned if there is no connectivity to any network. 
 
    \t \t * This is set to true under two circumstances: 
 
    \t \t * <ul> 
 
    \t \t * <li>When connectivity is lost to one network, and there is no other 
 
    \t \t * available network to attempt to switch to.</li> 
 
    \t \t * <li>When connectivity is lost to one network, and the attempt to 
 
    \t \t * switch to another network fails.</li> 
 
    \t \t */ 
 
    \t \t NOT_CONNECTED 
 
    \t } 
 

 
    \t /** 
 
    \t * Create a new NetworkConnectivityListener. 
 
    \t */ 
 
    \t public NetworkConnectivityListener() { 
 
    \t \t mState = State.UNKNOWN; 
 
    \t \t mReceiver = new ConnectivityBroadcastReceiver(); 
 
    \t } 
 

 
    \t /** 
 
    \t * This method starts listening for network connectivity state changes. 
 
    \t * 
 
    \t * @param context 
 
    \t */ 
 
    \t public synchronized void startListening(Context context,Bus bus) { 
 
    \t \t if (!mListening) { 
 
    \t \t \t mContext = context; 
 
    \t \t \t mThreadBus=new MainThreadBus(bus); 
 
    \t \t \t IntentFilter filter = new IntentFilter(); 
 
    \t \t \t filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
 
    \t \t \t context.registerReceiver(mReceiver, filter); 
 
    \t \t \t mListening = true; 
 

 
    \t \t } 
 
    \t } 
 

 
    \t /** 
 
    \t * This method stops this class from listening for network changes. 
 
    \t */ 
 
    \t public synchronized void stopListening() { 
 
    \t \t if (mListening) { 
 
    \t \t \t mContext.unregisterReceiver(mReceiver); 
 
    \t \t \t mContext = null; 
 
    \t \t \t mNetworkInfo = null; 
 
    \t \t \t mOtherNetworkInfo = null; 
 
    \t \t \t mIsFailover = false; 
 
    \t \t \t mReason = null; 
 
    \t \t \t mThreadBus=null; 
 
    \t \t \t mListening = false; 
 
    \t \t } 
 
    \t } 
 

 
    \t public State getState() { 
 
    \t \t return mState; 
 
    \t } 
 

 
    \t /** 
 
    \t * Return the NetworkInfo associated with the most recent connectivity 
 
    \t * event. 
 
    \t * 
 
    \t * @return {@code NetworkInfo} for the network that had the most recent 
 
    \t *   connectivity event. 
 
    \t */ 
 
    \t public NetworkInfo getNetworkInfo() { 
 
    \t \t return mNetworkInfo; 
 
    \t } 
 

 
    \t /** 
 
    \t * If the most recent connectivity event was a DISCONNECT, return any 
 
    \t * information supplied in the broadcast about an alternate network that 
 
    \t * might be available. If this returns a non-null value, then another 
 
    \t * broadcast should follow shortly indicating whether connection to the 
 
    \t * other network succeeded. 
 
    \t * 
 
    \t * @return NetworkInfo 
 
    \t */ 
 
    \t public NetworkInfo getOtherNetworkInfo() { 
 
    \t \t return mOtherNetworkInfo; 
 
    \t } 
 

 
    \t /** 
 
    \t * Returns true if the most recent event was for an attempt to switch over 
 
    \t * to a new network following loss of connectivity on another network. 
 
    \t * 
 
    \t * @return {@code true} if this was a failover attempt, {@code false} 
 
    \t *   otherwise. 
 
    \t */ 
 
    \t public boolean isFailover() { 
 
    \t \t return mIsFailover; 
 
    \t } 
 

 
    \t /** 
 
    \t * An optional reason for the connectivity state change may have been 
 
    \t * supplied. This returns it. 
 
    \t * 
 
    \t * @return the reason for the state change, if available, or {@code null} 
 
    \t *   otherwise. 
 
    \t */ 
 
    \t public String getReason() { 
 
    \t \t return mReason; 
 
    \t } 
 

 
    \t public boolean iswifiConnected() { 
 
    \t \t return isWifiConnected; 
 
    \t } 
 

 
    \t public boolean ismobileConnected() { 
 
    \t \t return isMobileConnected; 
 
    \t } 
 

 
    \t public class MainThreadBus extends Bus { 
 
    \t \t private final Bus mBus; 
 
    \t \t private final Handler mHandler = new Handler(Looper.getMainLooper()); 
 

 
    \t \t public MainThreadBus(final Bus bus) { 
 
    \t \t \t if (bus == null) { 
 
    \t \t \t \t throw new NullPointerException("bus must not be null"); 
 
    \t \t \t } 
 
    \t \t \t mBus = bus; 
 
    \t \t } 
 

 
    \t \t @Override 
 
    \t \t public void post(final Object event) { 
 
    \t \t \t System.out.println("Printing the Value of Send" + event); 
 
    \t \t \t if (Looper.myLooper() == Looper.getMainLooper()) { 
 
    \t \t \t \t mBus.post(event); 
 
    \t \t \t } else { 
 
    \t \t \t \t mHandler.post(new Runnable() { 
 
    \t \t \t \t \t @Override 
 
    \t \t \t \t \t public void run() { 
 
    \t \t \t \t \t \t mBus.post(event); 
 
    \t \t \t \t \t } 
 
    \t \t \t \t }); 
 
    \t \t \t } 
 
    \t \t } 
 
    \t } 
 
    }

我在这里使用otto,但您可以使用侦听器。

1

或者,您可以使用TinyBus开源项目,这使得您的代码就像这样简单。

public class MyActivity extends Activity { 

    private Bus mBus; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mBus = TinyBus.from(this).wire(new ConnectivityEvents()); 
     ... 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     mBus.register(this); 
    } 

    @Override 
    protected void onStop() { 
     mBus.unregister(this); 
     super.onStop(); 
    } 

    @Subscribe 
    public void onConnectivityEvent(ConnectionChangedEvent event) { 
     if (event.isConnected()) { 
      // connected 

     } else { 
      // disconnected 

     } 
    } 

    ... 
}