2014-08-31 73 views
0

在我的應用程序,我有4個活動。如果有任何網絡更改,我想更新處於前景狀態的活動。我爲網絡變化寫了一個廣播接收器。但我想更新來自該廣播接收器的活動。在android如何更新活動,如果任何網絡變化

這是我的廣播接收器:

public class NetworkChangeReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(final Context context, final Intent intent) { 
     final ConnectivityManager connMgr = (ConnectivityManager) context 
       .getSystemService(Context.CONNECTIVITY_SERVICE); 

     final android.net.NetworkInfo wifi = connMgr 
       .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 

     final android.net.NetworkInfo mobile = connMgr 
       .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

     if (wifi.isAvailable() || mobile.isAvailable()) { 
      // i need to update activity ????? 
     } 
    } 
} 
+0

發送特殊意圖的活動來更新它。但關於「更新活動」的問題非常廣泛。 – Array 2014-08-31 12:46:40

+0

如果網絡不可用,則需要顯示沒有網絡連接。 – user3860944 2014-08-31 12:47:25

+0

好的,你想改變顯示網絡狀態的文字嗎? – 2014-08-31 12:48:30

回答

0

在manifest文件中:

<application 
    android:name=".MyApp" 
    .... 
</application> 

然後建立這個類來保存當前活動場景:

public class MyApp extends Application { 
    public void onCreate() { 
      super.onCreate(); 
    } 

    private static Activity mCurrentActivity = null; 
    public static Activity getCurrentActivity(){ 
      return mCurrentActivity; 
    } 
    public static void setCurrentActivity(Activity mCurrentActivity){ 
      this.mCurrentActivity = mCurrentActivity; 
    } 
} 

創建新活動:

public class MyBaseActivity extends Activity { 
    protected MyApp mMyApp; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mMyApp = (MyApp)this.getApplicationContext(); 
    } 
    protected void onResume() { 
     super.onResume(); 
     mMyApp.setCurrentActivity(this); 
    } 
    protected void onPause() { 
     clearReferences(); 
     super.onPause(); 
    } 
    protected void onDestroy() {   
     clearReferences(); 
     super.onDestroy(); 
    } 

    private void clearReferences(){ 
     Activity currActivity = mMyApp.getCurrentActivity(); 
     if (currActivity != null && currActivity.equals(this)) 
      mMyApp.setCurrentActivity(null); 
    } 
} 

則:

public class NetworkChangeReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(final Context context, final Intent intent) { 
     final ConnectivityManager connMgr = (ConnectivityManager) context 
       .getSystemService(Context.CONNECTIVITY_SERVICE); 

     final android.net.NetworkInfo wifi = connMgr 
       .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 

     final android.net.NetworkInfo mobile = connMgr 
       .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

     if (wifi.isAvailable() || mobile.isAvailable()) { 
      // i need to update activity ????? 
      TextView tv = (TextView)myApp.getCurrentActivity().findViewById(R.id.your_view_id); 
      tv.setText("Network is available"); 
     } 
    } 
} 
相關問題