我正在android中开发一个从数据库中获取数据的应用程序。我开发了代码来查找WIFI或Mobile数据是打开还是关闭,如下所示:
protected boolean isNetworkAvailable()
{
boolean connection=true;
ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] activeNetworkInfo=connectivityManager.getAllNetworkInfo();
for(NetworkInfo ni:activeNetworkInfo)
{
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
if(ni.isConnected())
haveConnectedWifi=true;
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
if(ni.isConnected())
haveConnectedMobile=true;
}
if(haveConnectedWifi==false && haveConnectedMobile==false)
{
connection=false;
}
return connection;
}
现在假设我的WIFI或移动数据网络已开启,但我根本没有连接到互联网(WIFI未连接到任何接入点)。如何在Android中显示?
谢谢,
答案 0 :(得分:2)
你可以简单地使用它:
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
答案 1 :(得分:1)
这个课程非常完整:
public class ConnexionDetector extends BroadcastReceiver {
/**
* ATTRIBUTES
*/
private Context _context;
private boolean _noConnectivity;
private String _reason;
private boolean _isFailover;
private static boolean _isConnected = false;
private static boolean _isConnectivityGood = true;
public ConnexionDetector(Context context) {
this._context = context;
}
public void registerReceivers() {
_context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public static NetworkInfo getNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
public static boolean isConnected(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected());
}
public static boolean isConnectedWifi(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
public static boolean isConnectedMobile(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
public static boolean isConnectedFast(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype()));
}
private static boolean isConnectionFast(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return true;
}
else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
return false;
}
}
else {
return false;
}
}
@Override
public void onReceive(Context context, Intent intent) {
_noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
_reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
_isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
//
if (_noConnectivity) {
_isConnected = false;
}
else {
if (isConnectedFast(_context)) {
_isConnectivityGood = true;
}
else {
_isConnectivityGood = false;
}
_isConnected = true;
}
}
}
答案 2 :(得分:0)
试试这个,
ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()||mobile.isConnected())
return true;
else if (wifi.isConnected() && mobile.isConnected())
return true;
else
return false;
} catch (NullPointerException e) {
Log.d("ConStatus", "No Active Connection");
return false;
}
答案 3 :(得分:0)
此代码可能会对您有所帮助。
ConnectivityManager cn= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
testwifi=networkInfo.isConnected();
if(!testwifi)
tv1.setText("wifi is off");
else
tv1.setText("wifi is on");
答案 4 :(得分:0)
试试这个:
public static void isNetworkAvailable(Context context){
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try{
Log.d(TAG, "Checking network connection...");
httpClient.execute(httpGet);
Log.d(TAG, "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.d(TAG, "Connection unavailable");
}
答案 5 :(得分:0)
调用此类的isConnectingToInternet函数来检查您想要检查互联网连接的互联网连接。
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
答案 6 :(得分:0)
要确保实际互联网可用或不需要ping任何全局网址,例如 www.google.com
这将100%
public static boolean isNetwokReachable() {
final ConnectivityManager connMgr = (ConnectivityManager) mSmartAndroidActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10 * 1000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (Throwable e) {
return false;
}
} else {
return false;
}
}
答案 7 :(得分:0)
我也在搜索这个问题的答案,然后我在我的代码中做到了,它可以工作。不知道是好是坏。如果有什么问题,请告诉我。
步骤:1 创建一个 BaseActivity class 并扩展 AppCompatActivity class 并在其中编写代码以进行网络检查,并在出现以下情况时向用户显示消息没有网络连接:
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
open class BaseActivity : AppCompatActivity() {
private var cManager: ConnectivityManager? = null
private var mCallback: ConnectivityManager.NetworkCallback? = null
private var request : NetworkRequest? = null
private var view: View? = null
private var mSnackBar: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
request = NetworkRequest.Builder().build()
// get root view where we want to show message
view = window.decorView.rootView
mCallback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
super.onLost(network)
mSnackBar = Snackbar.make(view!!, "No Network connection", Snackbar.LENGTH_LONG)
mSnackBar!!.duration = Snackbar.LENGTH_INDEFINITE
mSnackBar!!.show()
}
override fun onAvailable(network: Network) {
super.onAvailable(network)
if (mSnackBar != null){
mSnackBar!!.dismiss()
}
}
}
cManager!!.registerNetworkCallback(request!!, mCallback!!)
}
override fun onStop() {
super.onStop()
cManager!!.unregisterNetworkCallback(mCallback!!)
}
}
第2步:
现在在 MainActivity 类中,扩展了此 BaseActivity 类。
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
第3步: 不要忘记将其添加到 AndroidManifest 文件
中<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
现在运行并检查您的应用程序。 :)