从静态BroadCastReciever更新UI

时间:2016-08-10 14:49:30

标签: android

我已经检查了如何处理网络连接更改的示例: Android Check Internet Connection并找到了一段非常好的代码来处理这些变化:

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = NetworkUtil.getConnectivityStatusString(context); //some internal class to determinate which type is connected

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }
}

为了使这个工作正常,我需要在清单文件中声明这个BroadCastReciever:

<application  ...>
     ...
        <receiver
            android:name="net.viralpatel.network.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
      ...
</application>

现在我想在连接wifi /移动数据时更新UI。

我可以使NetworkChangeReceiver类内部静态或外部。但我需要的是,我可以使用来自MainActivity的{​​{1}}用户界面。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

答案很简单。我不需要注册我的广播,以获得有关连接变化的广播:

private BroadcastReceiver networkConnectivityReciever = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (dialog != null) {
                if(currentNetworkInfo.isConnected()){
                    dialog.dismiss();
                    webView.reload();
                }else{
                    dialog.show(((MainActivity) context).getSupportFragmentManager(), "");
                }
            }
        }
    };

@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(networkConnectivityReciever,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(networkConnectivityReciever);
    }

我在清单中唯一需要的是:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />