获取每个活动的网络状态

时间:2017-06-15 16:09:18

标签: java android android-activity broadcastreceiver android-broadcast

我正在实施一个需要互联网连接的应用。如果没有互联网连接,将根据活动以不同的方式显示“无连接”消息。

为此,我有以下课程:

public class NetworkAvailability {

    private static final String NETWORK_AVAILABILITY_ACTION = "com.toast.NETWORK_AVAILABILITY_ACTION";

    private ConnectivityManager connectivityManager;
    private ConnectivityManager.NetworkCallback networkCallback;

    private static NetworkAvailability instance;

    private NetworkAvailability() {
    }

    public static NetworkAvailability getInstance(){
        if(instance == null){
            instance = new NetworkAvailability();
        }
        return instance;
    }

    private static boolean isAvailable(Context context) {
        ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }

    public void registerNetworkAvailability(final Context context, BroadcastReceiver networkAvailabilityReceiver) {

        context.registerReceiver(networkAvailabilityReceiver, new IntentFilter(NETWORK_AVAILABILITY_ACTION));

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            context.registerReceiver(connectivityChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        } else{
            connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkRequest.Builder builder = new NetworkRequest.Builder();
            networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    context.sendBroadcast(getNetworkAvailabilityIntent(true));
                }

                @Override
                public void onLost(Network network) {
                    context.sendBroadcast(getNetworkAvailabilityIntent(false));
                }
            };
            connectivityManager.registerNetworkCallback(builder.build(), networkCallback);
            if(isAvailable(context)){
                context.sendBroadcast(getNetworkAvailabilityIntent(true));
            } else{
                context.sendBroadcast(getNetworkAvailabilityIntent(false));
            }
        }
    }

    public void unregisterNetworkAvailability(Context context, BroadcastReceiver networkAvailabilityReceiver){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            context.unregisterReceiver(connectivityChangeReceiver);
        } else{
            connectivityManager.unregisterNetworkCallback(networkCallback);
        }
        context.unregisterReceiver(networkAvailabilityReceiver);
    }

    public BroadcastReceiver connectivityChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(@NonNull Context context, @NonNull Intent intent) {
            if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
                context.sendBroadcast(getNetworkAvailabilityIntent(false));
            } else {
                context.sendBroadcast(getNetworkAvailabilityIntent(true));
            }
        }
    };

    @NonNull
    private Intent getNetworkAvailabilityIntent(boolean isNetworkAvailable) {
        Intent intent = new Intent(NETWORK_AVAILABILITY_ACTION);
        intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, !isNetworkAvailable);
        return intent;
    }
}

我现在如何使用每个活动中的BroadcastReceiver?

1 个答案:

答案 0 :(得分:0)

我所做的是在Manifest上设置broadcastReceiver:

    <receiver
        android:name=".data.sync.CatchConnectionChangesReceiver"
        android:label="Upload cached images broadcast receiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>

然后我上课了:

class CatchConnectionChangesReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (Util.isNetworkAvailable()) {
            // Do whatever you want to do when network is available
        }
    }
}

接收器将从每个活动中激活,您不需要在每个活动上注册它

在Util.isNetworkAvailable()中我和你的isAvailable()方法一样

根据第一条评论更新

如果你想做类似的事情:

if (isConnected) {
   // Do something here like view.setVisibility(View.Visible)
}

您只需公开您的isAvailable()方法,因为它已经是静态的,您可以从任何您想要的活动中执行此操作:

if (NetworkAvailability.isAvailable(this)) {
    // Do something here like view.setVisibility(View.Visible)
}

最后一件事你不需要广播接收器