2014-09-24 103 views
-2

我使用了獲取網絡status.I廣播接收器時,從另一個類的變量正在使用此代碼訪問使用廣播接收機

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變量來自主要活動班。我可以怎樣做?

+0

製作'static'變量並在'BroadcastReceiver'中訪問它....它有什麼問題? – 2014-09-24 10:16:36

+0

您可以將其設爲公共靜態或通過sharedpreferences保存/檢索它 – santalu 2014-09-24 10:17:26

回答

1

在主Activity中聲明networkStatuspublic static。訪問它使用,例如,MainActivity.networkStatus