使用广播接收器时从另一个类访问变量

时间:2014-09-24 10:14:04

标签: android

我正在使用广播接收器获取网络状态。我正在使用此代码

public class ConnectionChangeReceiver extends BroadcastReceiver
{

  public Boolean networkStatus=false;

  @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 )
    {
      networkStatus=true;
      Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
    if( mobNetInfo != null )
    {
      networkStatus=true;
      Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
  }

但是你知道这是另一个类,我必须从主要活动类中访问networkStatus变量。我该怎么做?

1 个答案:

答案 0 :(得分:1)

在主Activity中将networkStatus声明为public static。例如,使用MainActivity.networkStatus

访问它