广播接收机检查在Android应用程序的互联网连接

我正在开发一个android广播接收器来检查互联网连接。

问题是我的广播接收器被调用了两次。 我希望它只在networking可用时才被调用。 如果不可用,我不需要通知。

这是广播接收机

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()) { // Do something Log.d("Network Available ", "Flag No 1"); } } } 

这是manifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastreceiverforinternetconnection" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name=".NetworkChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> </application> </manifest> 

回答你的第一个问题 :你的广播接收机被称为两次,因为

你已经添加了两个<intent-filter>

  1. networking连接更改:
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  2. WiFi状态变化:
    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />

只需使用一个:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

它只会响应一个动作而不是两个。 在这里看到更多的信息。

回答你的第二个问题 (如果可用的互联网连接,你希望接收者只打一次):

你的代码是完美的; 只有在互联网可用时才通知您。

UPDATE

如果您只想检查移动设备是否与互联网连接,则可以使用此方法检查您的连接。

 public boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); //should check null because in airplane mode it will be null return (netInfo != null && netInfo.isConnected()); } 
 public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if(checkInternet(context)) { Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); } } boolean checkInternet(Context context) { ServiceManager serviceManager = new ServiceManager(context); if (serviceManager.isNetworkAvailable()) { return true; } else { return false; } } } 

ServiceManager.java

 public class ServiceManager { Context context; public ServiceManager(Context base) { context = base; } public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } } 

权限:

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

使用此方法检查networking状态:

 private void checkInternetConnection() { if (br == null) { br = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); NetworkInfo info = (NetworkInfo) extras .getParcelable("networkInfo"); State state = info.getState(); Log.d("TEST Internet", info.toString() + " " + state.toString()); if (state == State.CONNECTED) { Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show(); } } }; final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver((BroadcastReceiver) br, intentFilter); } } 

记得在onDestroy中取消注册服务。

干杯!!

检查Intenert每次使用广播接收器像Youtube一样去在线,离线

在这里输入图像说明 源代码

https://drive.google.com/open?id=0BzBKpZ4nzNzUYjhZamFIZTh6VTQ

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/> <receiver android:name=".receivers.NetworkChangeReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> =============================================================== package com.keshav.networkchangereceiverexample.receivers; 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 static com.keshav.networkchangereceiverexample.MainActivity.dialog; public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { if (isOnline(context)) { dialog(true); Log.e("keshav", "Online Connect Intenet "); } else { dialog(false); Log.e("keshav", "Conectivity Failure !!! "); } } catch (NullPointerException e) { e.printStackTrace(); } } private boolean isOnline(Context context) { try { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); //should check null because in airplane mode it will be null return (netInfo != null && netInfo.isConnected()); } catch (NullPointerException e) { e.printStackTrace(); return false; } } } ================================================================= package com.keshav.networkchangereceiverexample; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver; public class MainActivity extends AppCompatActivity { private BroadcastReceiver mNetworkReceiver; static TextView tv_check_connection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_check_connection=(TextView) findViewById(R.id.tv_check_connection); mNetworkReceiver = new NetworkChangeReceiver(); registerNetworkBroadcastForNougat(); } public static void dialog(boolean value){ if(value){ tv_check_connection.setText("We are back !!!"); tv_check_connection.setBackgroundColor(Color.GREEN); tv_check_connection.setTextColor(Color.WHITE); Handler handler = new Handler(); Runnable delayrunnable = new Runnable() { @Override public void run() { tv_check_connection.setVisibility(View.GONE); } }; handler.postDelayed(delayrunnable, 3000); }else { tv_check_connection.setVisibility(View.VISIBLE); tv_check_connection.setText("Could not Connect to internet"); tv_check_connection.setBackgroundColor(Color.RED); tv_check_connection.setTextColor(Color.WHITE); } } private void registerNetworkBroadcastForNougat() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } } protected void unregisterNetworkChanges() { try { unregisterReceiver(mNetworkReceiver); } catch (IllegalArgumentException e) { e.printStackTrace(); } } @Override public void onDestroy() { super.onDestroy(); unregisterNetworkChanges(); } } ============================================================== activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.keshav.networkchangereceiverexample.MainActivity"> <TextView android:id="@+id/tv_check_connection" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Connection establised !" android:padding="25dp" app:layout_constraintBottom_toBottomOf="parent" android:gravity="center" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </LinearLayout> 
 public static boolean isNetworkAvailable(Context context) { boolean isMobile = false, isWifi = false; NetworkInfo[] infoAvailableNetworks = getConnectivityManagerInstance( context).getAllNetworkInfo(); if (infoAvailableNetworks != null) { for (NetworkInfo network : infoAvailableNetworks) { if (network.getType() == ConnectivityManager.TYPE_WIFI) { if (network.isConnected() && network.isAvailable()) isWifi = true; } if (network.getType() == ConnectivityManager.TYPE_MOBILE) { if (network.isConnected() && network.isAvailable()) isMobile = true; } } } return isMobile || isWifi; } /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */ public class NetworkChangedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (isNetworkAvailable(context)) { Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); } } } 

以上广播接收机只有在networking状态改变连接而不连接时才会被呼叫。

我知道这个线程是老的和完全的答案,但我觉得以下可能会帮助一些人。

问题正文中的代码包含一个这里没有人提到的错误。 @Nikhil正在检查wifi / mobile是否可用,而不是连接。

修正在这里:

 @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.isConnected() || mobile.isConnected()) { // do stuff } } 

试试这个

 public class ConnectionBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (<Check internet connection available >) { Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show(); /*upload background upload service*/ Intent serviceIntent = new Intent(context,<your service class>); context.startService(serviceIntent); }else{ Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show(); } } } 

这是广播接收机。 互联网连接触发器即将加载

performance:

 <receiver android:name=".your.namepackage.here.ConnectivityReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </receiver> 

接收器类:

 public class ConnectivityReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); switch (action) { case ConnectivityManager.CONNECTIVITY_ACTION: DebugUtils.logDebug("BROADCAST", "network change"); if(NetworkUtils.isConnect()){ //do action here } break; } } } 

并像例子一样对utils进行分类:

 public class NetworkUtils { public static boolean isConnect() { ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Network[] netArray = connectivityManager.getAllNetworks(); NetworkInfo netInfo; for (Network net : netArray) { netInfo = connectivityManager.getNetworkInfo(net); if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) { //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) { Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName()); return true; } } } else { if (connectivityManager != null) { @SuppressWarnings("deprecation") NetworkInfo[] netInfoArray = connectivityManager.getAllNetworkInfo(); if (netInfoArray != null) { for (NetworkInfo netInfo : netInfoArray) { if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) { //if (netInfo.getState() == NetworkInfo.State.CONNECTED) { Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName()); return true; } } } } } return false; } } 

添加一个可以监听networking连接变化的广播接收器。 然后检查其设备是否连接到互联网或不使用ConnectivityManager。 请参阅此post或video以获得详细的了解。 以下是代码:

 public class NetworkStateChangeReceiver extends BroadcastReceiver { public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable"; public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable"; @Override public void onReceive(Context context, Intent intent) { Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION); networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context)); LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent); } private boolean isConnectedToInternet(Context context) { try { if (context != null) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } return false; } catch (Exception e) { Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage()); return false; } } } 

我写了这个接收器在屏幕上显示通知,这就是为什么你看到一个本地广播的networking状态。 这是显示通知的代码。

 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false); String networkStatus = isNetworkAvailable ? "connected" : "disconnected"; Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show(); } }, intentFilter); } } 

活动监听networking接收器播放的意图,并在屏幕上显示通知。

 public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> { public static final int TIME_OUT = 10 * 1000; private OnCallBack listener; public interface OnCallBack { public void onBack(Boolean value); } public AsyncCheckInternet(OnCallBack listener) { this.listener = listener; } @Override protected void onPreExecute() { } @Override protected Boolean doInBackground(String... params) { ConnectivityManager connectivityManager = (ConnectivityManager) General.context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if ((networkInfo != null && networkInfo.isConnected()) && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo .getType() == ConnectivityManager.TYPE_MOBILE))) { HttpURLConnection urlc; try { urlc = (HttpURLConnection) (new URL("http://www.google.com") .openConnection()); urlc.setConnectTimeout(TIME_OUT); urlc.connect(); if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else { return false; } } catch (MalformedURLException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } } else { return false; } } @Override protected void onPostExecute(Boolean result) { if (listener != null) { listener.onBack(result); } } 

}

只是想要dynamic注册广播的其他人:

 BroadcastReceiver mWifiReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (checkWifiConnect()) { Log.d(TAG, "wifi has connected"); // TODO } } }; private void registerWifiReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mContext.registerReceiver(mWifiReceiver, filter); } private void unregisterWifiReceiver() { mContext.unregisterReceiver(mWifiReceiver); } private boolean checkWifiConnect() { ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) { return true; } return false; } 

CONNECTIVITY_ACTION文档 :

面向Android 7.0(API级别24)及更高版本的应用程序如果在其清单中声明广播接收器,则不会收到此广播。 如果使用Context.registerReceiver()注册BroadcastReceiver,并且该上下文仍然有效,应用程序仍然会收到广播。

广播接收器代码来检查互联网连接变化:

 public class BroadCastDetecter extends BroadcastReceiver { public static boolean internet_status = false; public static void checkInternetConenction(Context context) { internet_status = false; ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (check != null) { NetworkInfo[] info = check.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { internet_status = true; } } if(internet_status) { //do what you want to if internet connection is available } } } @Override public void onReceive(Context context, Intent intent) { try { checkInternetConenction(context); }catch(Exception e){ } } } 

在清单文件中添加这个:

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