Android 使用广播接收器时从另一个类访问变量
我正在使用广播接收器获取网络状态。我正在使用此代码Android 使用广播接收器时从另一个类访问变量,android,Android,我正在使用广播接收器获取网络状态。我正在使用此代码 public class ConnectionChangeReceiver extends BroadcastReceiver { public Boolean networkStatus=false; @Override public void onReceive( Context context, Intent intent ) { ConnectivityManager connectivityManager
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
变量。我如何才能做到这一点?在主活动中将networkStatus
声明为公共静态
。例如,使用MainActivity.networkStatus
使static
变量并在BroadcastReceiver
中访问它。。。。有什么问题吗?您可以将其公开为静态的,也可以通过SharedReferences保存/检索它