java 从主要活动检查互联网状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28168867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check internet status from the main activity
提问by mohamd jado
I'm new student on android development, so I don't have the enough experience for coding, so I need the help from you... I create a java class on android studio to check if there is an internet connection or not :
我是android开发的新学生,所以我没有足够的编码经验,所以我需要你的帮助......我在android studio上创建了一个java类来检查是否有互联网连接:
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class InternetStatus {
private static final String LOG_TAG ="InternetStatus";
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable((Activity) context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Activity mActivity) {
Context context = mActivity.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
}
So, I have two questions :
所以,我有两个问题:
1- is this the right code or I'm missing something ?
1-这是正确的代码还是我遗漏了什么?
2- as you see this is a java class, if I create a button on my main activity to check if there is an internet connection or not !! how I can do that by importing this class or something like that ?!!
2- 如您所见,这是一个 Java 类,如果我在主要活动上创建一个按钮来检查是否有互联网连接!!我怎么能通过导入这个类或类似的东西来做到这一点?!
回答by Anggrayudi H
// Check if there is any connectivity for a Wifi network
public boolean isConnectedWifi(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
if (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI){
return true;
}
return false;
}
// Check if there is any connectivity for a mobile network
public boolean isConnectedMobile(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
if(info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE){
return true;
}
return false;
}
// Check all connectivities whether available or not
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;
}
How to use?
如何使用?
For example, we need to check if the connectivity is available:
例如,我们需要检查连接是否可用:
if(isNetworkAvailable()){
// do your thing here.
}
When the network is available, we need to check whether it is WiFi or Mobile network:
当网络可用时,我们需要检查是WiFi还是Mobile网络:
if(isConnectedWifi()){
// do your thing here with WiFi Network.
}
if(isConnectedMobile()){
// do your thing here with Mobile Network.
}
回答by Silvio Delgado
First of all, you must include a permission request in AndroidManifest.xml
首先必须在AndroidManifest.xml中包含一个权限请求
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then, create a methodto check if internet connection is active:
然后,创建一个方法来检查互联网连接是否处于活动状态:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
回答by San
Most of the answers are outdated
大多数答案已经过时
fun isNetworkAvailable(context : Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (isAndroidVersionAboveLollipop()) {
val activeNetwork = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
networkCapabilities.let {
return it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && it.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
} else {
return connectivityManager.activeNetworkInfo?.isConnectedOrConnecting ?: false
}
}
fun isAndroidVersionAboveLollipop() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
回答by Murtaza Khursheed Hussain
In your MainActivity
class
在你的MainActivity
班级
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
boolean isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
}
}
if you have a button
如果你有一个按钮
boolean isavailable ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
Button someButton = (Button) findViewById(R.id.yourButton);
someButton.setOnClickListener(new onClickLIstener(){
isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
});
}
}
回答by Vilas
To check the connectivity status no need to connect to internet and get status code. Use below code.
要检查连接状态,无需连接到互联网并获取状态代码。使用下面的代码。
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Which will return true or false based on active network status.
这将根据活动网络状态返回 true 或 false。
On your button click simply call this function, If it returns true, there is a connection. If it returns false, there is no active internet connection.
在您的按钮上单击只需调用此函数,如果返回 true,则表示存在连接。如果返回 false,则表示没有活动的 Internet 连接。
回答by arpit
Just Put info.isConnected() in your isNetworkAvailable function:
只需将 info.isConnected() 放在您的 isNetworkAvailable 函数中:
public static boolean isNetworkAvailable(Activity mActivity) {
...
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null && info.isConnected()) {
...
}
}
}
return false;
}