如何使用CONNECTIVITY_CHANGE定义Broadcastreceiver?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用CONNECTIVITY_CHANGE定义Broadcastreceiver?相关的知识,希望对你有一定的参考价值。

我是android初学者,想要声明一个对CONNECTIVITY_CHANGE作出反应的broadcastreceiver。我尝试过以下方法:

private void checkInternet () {
    IntentFilter ifilter = new IntentFilter ("android.net.conn.CONNECTIVITY_CHANGE");
    broadcastreceiver = new BroadcastReceiver () {
        @Override
        public void onReceive (Context Context, Intent Intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService (getApplicationContext (). CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo ();
            if (networkInfo! = null && networkInfo.getState () == NetworkInfo.State.CONNECTED)
                Toast.makeText (getApplicationContext (), "Internet", Toast.LENGTH_SHORT) .show ();
            else
                Toast.makeText (getApplicationContext (), "No Internet", Toast.LENGTH_SHORT) .show ();
        }
    };
    this.registerReceiver (broadcastreceiver, ifilter);
}

在Actitvity.onCreate中,我调用checkInternet。当我断开互联网时,会显示“无互联网”和“互联网”两条消息。当我连接互联网时,“无互联网”和“互联网”这两条消息再次以相同的顺序出现。有人可以告诉我为什么Broadcastreceiver 2次启动并显示2个不同的状态亲开始?我提前谢谢你

答案

请尝试以下示例:

执行:

public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                Log.d("Network status: ", "Connected");
            } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
                Log.d("Network status: ", "Not connected");
            }
        }
    }
}

在AndroidManifest中添加接收器:

<receiver
    android:name=".receivers.NetworkReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
另一答案

如果您只需要检查互联网连接,可以使用以下内容。在你的活动中

 @Override
 protected void onCreate(Bundle savedInstanceState){
       ConnectionStateMonitor connectionStateMonitor = new ConnectionStateMonitor();
    connectionStateMonitor.enable(this);
 }

并在您的活动中添加此类

public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {

    final NetworkRequest networkRequest;

    public ConnectionStateMonitor() {
        networkRequest = new NetworkRequest.Builder().
                addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
    }

    public void enable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(networkRequest , this);
    }
    // Likewise, you can have a disable method that simply calls ConnectivityManager#unregisterCallback(networkRequest) too.

    @Override
    public void onAvailable(Network network) {
         //do what you want when Connection is available
    }
    @Override
    public void onLost(Network network){
        //Connection Lost
    }
}

我认为这比使用broadCast接收器更容易

另一答案

创建一个将从BroadcastReceiver扩展的新类。在此处定义连接更改的intent过滤器。我们还创建了一个新的私有方法来检索网络连接的当前状态。

public class ConnectivityChangedBroadcastReceiver extends BroadcastReceiver {

public static IntentFilter getIntentFilter() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    return intentFilter;
}

@Override
public void onReceive(Context context, Intent intent) {
    if (isNetworkAvailable(context)) {
        // Network is available
    } else {
        // Network is not available
    }
}

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}}

现在在活动或应用程序类中注册您的广播接收器。请注意,针对Android 7.0(API级别24)及更高版本的应用如果在其清单中声明广播接收器,则不会收到CONNECTIVITY_ACTION广播。如果应用程序使用Context.registerReceiver()注册其BroadcastReceiver并且该上下文仍然有效,则仍会收到CONNECTIVITY_ACTION广播。因此,如果您想要定位最新版本的Android,请确保在代码中注册接收器而不是显示

ConnectivityChangedBroadcastReceiver connectivityChangedBroadcastReceiver;
connectivityChangedBroadcastReceiver = new ConnectivityChangedBroadcastReceiver();
registerReceiver(connectivityChangedBroadcastReceiver, ConnectivityChangedBroadcastReceiver.getIntentFilter());
另一答案

如上所述,所有解决方案都有效,问题是VM。当我在计算机上断开Internet连接时,VM仍然具有物理连接,但只能进行通信。因此,在我的PC上断开连接或连接时,按此顺序显示消息“未连接”“已连接”

以上是关于如何使用CONNECTIVITY_CHANGE定义Broadcastreceiver?的主要内容,如果未能解决你的问题,请参考以下文章

android.net.conn.CONNECTIVITY_CHANGE 问题

CONNECTIVITY_CHANGE在Android N的目标中已弃用

如何在android上获取网络状态变化? [复制]

应用程序关闭时如何接收 Android Nougat 网络丢失的回调?

网络在线监控 [重复]

连接 Wifi 时收到两次 CONNECTIVITY_ACTION 意图