广播接收器检测networking已连接

我试图得到用户连接到networking的时刻,然后我认为BroadcastReceiver是一个好方法…我想要做的事情是,当用户连接到networking知道这个networking有连接互联网。

主要的是知道WiFi是否需要Browse Log in示例: Handling Network Sign-On文档

我到目前为止试过了什么?

我已经改变了我的BroadcastReceiver

 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", "Internet YAY"); } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) { if (isNetworkOnline()) { Log.d(TAG, String.valueOf(tikis)); NetTask TeInternet = new NetTask(); TeInternet.execute("https://www.google.com"); } } 

问题是,当我尝试连接到没有Internet ConnectionWiFiinput是这样的:

 D/Network﹕ Internet YAY D/Network﹕ Internet YAY D/Network﹕ Internet YAY D/RequiresLoginBroadcast﹕ 1 //this occurs sometimes 

我已经将Inner Class更改为Handling Network Sign-On文档

doInBackground()方法:

 protected Boolean doInBackground(String...params) { boolean internetAccessExists = false; String urlToBeAccessed = params[0]; final int TIMEOUT_VALUE_IN_MILLISECONDS = 15000; URL url; HttpURLConnection urlConnection = null; try { url = new URL(urlToBeAccessed); urlConnection = (HttpURLConnection) url.openConnection(); //set the respective timeouts for the connection urlConnection.setConnectTimeout(TIMEOUT_VALUE_IN_MILLISECONDS); urlConnection.setReadTimeout(TIMEOUT_VALUE_IN_MILLISECONDS); //the redirect check is valid only after the response headers have been received //this is triggered by the getInputStream() method InputStream in = new BufferedInputStream(urlConnection.getInputStream()); if (!url.getHost().equals(urlConnection.getURL().getHost())) { internetAccessExists = true; } } //any sort of exception is considered as a redirect. //more specific exceptions such as SocketTimeOutException and IOException can be handled as well catch (Exception e) { Log.d(TAG, e.toString()); } finally { Log.d(TAG, "Finally"); urlConnection.disconnect(); } return internetAccessExists; 

到目前为止我所寻找的是什么?

  1. 如何检测何时在Android中build立WIFI连接?
  2. Android WIFI如何检测特定的WIFI连接可用
  3. BroadcastReceiver不工作(检测是否连接了WiFi)

还有更多…但是,我没有find正确的答案给我。

TL; DR

我试图做的事情是获得用户连接到networking的确切事件,然后得到一个很好的方法来检测,如果我可以做一个谷歌ping或检查是否有连接到互联网(只有WIFI,3G连接是不允许的) ,因为我目前使用的代码有时会失败…

我认为这是一个很好的方法来知道,如果有Internet Connection因为我想知道的东西是检测如果Wifi需要浏览器login。

我们已经差不多完成了…但是我不明白为什么要进入BroadcastReceiver 4次甚至5次….有时候说有没有Internet connection时候…

Solutions Collecting From Web of "广播接收器检测networking已连接"

这是我目前正在使用的,它的工作完美。 当互联网连接时,我会收到通知(不仅打开,当有一个实际的互联网连接)。
它也适用于任何types的数据连接,但可以很容易地修改为只接受WiFi,3G,4G等。

码:

 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", "Internet YAY"); } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) { Log.d("Network", "No internet :("); } } } } 

performance:

 <receiver android:name=".receivers.NetworkReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> 
 public abstract class NetworkReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (null != intent) { State wifiState = null; State mobileState = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) { // phone network connect success gNetwork(); } else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) { // no network noNetwork(); } else if (wifiState != null && State.CONNECTED == wifiState) { // wift connect success WIFINetwork(); } } } 

}

清单集

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

您需要的所有内容都包含在本文档中: 确定和监控连接状态 。 也看看这个类: Connectivity.java

简言之,步骤应该如下:

1.截取CONNECTIVITY_CHANGE广播。

2.onReceive()方法中,检查是否存在互联网连接,以及是否为Wifi或GPRS。

这应该很容易实现,它应该没有任何问题的工作。 在某些情况下,与HTC和一些三星设备一样,如果核心操作系统已被修改,行为可能会有所不同。

每次使用Broadcast Receiver检查intenet

在这里输入图像说明

AndroidManifest.xml中

 <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> 

BroadcastReciever

 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> 

我试过这种方法(下面),它的工作。 尚未完全testing,但我使用类似的接收电池状态。 这样的代码less,它的工作。

 private BroadcastReceiver networkReceiver = new 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(LOG_TAG, "We have internet connection. Good to go."); } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) { Log.d(LOG_TAG, "We have lost internet connection"); } } } }; @Override protected void onResume() { super.onResume(); IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(networkReceiver, intentFilter); } @Override protected void onPause() { super.onPause(); if (networkReceiver != null) unregisterReceiver(networkReceiver); }