public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void show(View v){
if (hasActiveInternetConnection(context)){
Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show();
}
}
public boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
new URLConnectTask().execute();
} else {
// Log.d(LOG_TAG, "No network available!");
Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show();
}
return false;
}
private class URLConnectTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
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();
String code = String.valueOf(urlc.getResponseCode() == 200);
return code;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error checking internet connection", e);
//Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show();
return "Error checking internet connection";
}
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
我使用此post进行互联网连接检查。但由于他们没有使用asynctask,如果我使用这段代码,我会得到NetworkOnMainThreadException
。我尝试使用asynctask,但现在我只收到消息&#34;互联网连接不可用&#34;。我认为这是因为asynctask没有返回布尔值true。所以任何帮助都会非常感激。
答案 0 :(得分:3)
这项工作很好,你可以使用这段代码
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;
}
//add to permission <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:0)
试用此代码
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public void show(View v){
if (isConnectingToInternet(context)){
Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show();
new URLConnectTask().execute();
}else{
Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show();
}
}
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;
}
}
private class URLConnectTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
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();
String code = String.valueOf(urlc.getResponseCode() == 200);
return code;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error checking internet connection", e);
//Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show();
return "Error checking internet connection";
}
}
}
}
答案 2 :(得分:0)
使用波纹管方法在线查看
/ ***************** *检查isOnline ****************** /
public static boolean isOnline(Context context) {
boolean result = false;
if (context != null) {
final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null) {
result = networkInfo.isConnected();
}
}
}
return result;
}
确保您的清单包含此权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
答案 3 :(得分:0)
您可以使用此课程:
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;
}
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;
}
}
答案 4 :(得分:0)
尝试一次,
Boolean isInternetPresent = false;
isInternetPresent = findconn.isConnectingToInternet();
if (isInternetPresent) {
new URLConnectTask().execute();
} else {
// Log.d(LOG_TAG, "No network available!");
Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show();
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info=connectivity.getActiveNetworkInfo();
if (info == null) {
return false;
}
else {
return info.isConnectedOrConnecting();
}
}
(或)如果您需要单独的网络类型
ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
}
} else {
// not connected to the internet
}
答案 5 :(得分:0)
我编写了一个自定义类,用于检查所有可能的网络WIFI或移动数据。试试这个:
public class NetworkManager {
/**
* Checking for all possible internet providers
* **/
public static boolean isConnectingToInternet(Activity activity){
ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
}else {
if (connectivityManager != null) {
//noinspection deprecation
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
// LOGD(TAG, "NETWORKNAME: " + anInfo.getTypeName());
return true;
}
}
}
}
}
showInternetSettingsAlert(activity);
return false;
}
/**
* Display a dialog that user has no internet connection lauch Settings
* Options
* */
public static void showInternetSettingsAlert(final Activity activity) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle);
// Setting Dialog Title
alertDialog.setTitle("Internet Settings");
alertDialog.setCancelable(false);
// Setting Dialog Message
alertDialog
.setMessage("Internet is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(activity instanceof BaseFragmentActivity)
((BaseFragmentActivity)activity).hideLoader();
else if(activity instanceof BaseActivity)
((BaseActivity)activity).hideLoader();
// take user to turn Wifi screen
// activity.startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
// take user to turn on mobile data screen
activity.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
}
如果网络不可用,它会重定向用户以打开网络。
答案 6 :(得分:-1)
请检查清单文件中是否有此代码
<uses-permission android:name="android.permission.INTERNET" />
试试这个
ConnectivityManager cm = (ConnectivityManager)
activity.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;