应用启动时获取网络状态

时间:2014-09-23 12:35:59

标签: android

我想在应用启动时学习网络状态,我正在使用此代码

public class ConnectionChangeReceiver extends BroadcastReceiver
{
  @Override
  public void onReceive( Context context, Intent intent )
  {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(     ConnectivityManager.TYPE_MOBILE );
    Log.w("Network Status:",""+activeNetInfo);
    if ( activeNetInfo != null )
    {

      Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
    if( mobNetInfo != null )
    {
      Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
  }
}

但是只有当网络状态发生变化时才会调用。我需要知道应用程序启动时的网络状态。我该怎么做?

1 个答案:

答案 0 :(得分:0)

小代码示例:

public boolean isOnline()
{
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

不要忘记设置权限。

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