在android中如果任何网络更改如何更新活动

时间:2014-08-31 12:41:24

标签: android

在我的应用中,我有4项活动。如果有任何网络更改,我想更新处于前台状态的活动。我为网络变化写了一个广播接收器。但我想更新该广播接收器的活动。

这是我的广播接收器:

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 ?????
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在清单文件中:

<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");
        }
    }
}