简体   繁体   中英

Android: BroadcastReceiver for internet connection

I am trying to get my BroadcastReceiver to work but I have the problem when I disconnect the internet connection, I am getting the Toast "Please connect the device to the internet.", on the other hand I am getting the same Toast "Please connect the device to the internet." When I establish internet connection again. Is something wrong with the class?

 package com.bustracker; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import android.widget.Toast; public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting(); if (isConnected) { Toast.makeText(context, "The device is connected to the internet ", Toast.LENGTH_SHORT).show(); Log.i("NET", "connecte" +isConnected); } else { Toast.makeText(context, "Please connect the device to the internet.", Toast.LENGTH_SHORT).show(); } } } 

  <receiver android:name=".ConnectionChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> 

问题是您正在获得移动数据连接而不是wifi,因此即使设备已连接以获取当前的NetworkInfo ,它仍然会为您带来错误消息

NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM