我使用此方法ping go google服务器,因此我可以检查有效的internet
连接,但我发现它并不适用于所有设备。
我尝试过使用HttpURLConnection
和URLConnection
等其他方法,但即使我已经连接,它们都会返回false。
适用于所有设备的任何想法或解决方案。提前谢谢。我将连续发布我已经尝试过的内容。
方法1:
public static Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 8.8.8.8");
int returnVal = p1.waitFor();
return (returnVal == 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
我已尝试在本地和谷歌服务器上使用它,它可以产生完美的效果。问题是它无法在所有设备上运行。
方法2:
public boolean isConnected() {
boolean connectivity;
try {
URL url = new URL("www.google.com");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.connect();
connectivity = true;
} catch (Exception e) {
connectivity = false;
}
return connectivity;
}
尽管我的连接处于活动状态,但这个返回false。
方法3:
public static boolean isInternetReachable() {
try {
//make a URL to a known source
URL url = new URL("http://www.google.co.ke");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
与此相同。虚假值。
最后一个是这个班级,但它也做了同样的事情:
class TestInternet extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
connected = true;
return connected;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
connected = false;
return connected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
connected = false;
return connected;
}
return connected;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(CtgActivity.this);
builder.setMessage("An internet connection is required.");
builder.setCancelable(false);
builder.setPositiveButton(
"TRY AGAIN",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new TestInternet().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
Toast.makeText(CtgActivity.this,"Yes",Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPreExecute() {
Toast.makeText(getBaseContext(),"Checking for internet",Toast.LENGTH_LONG).show();
super.onPreExecute();
}
}
我经历过这样的事情,找到了我能做的一切,但一切都围绕着这些。请告诉我,如果这是我做错了或建议更好的解决方法。它是我项目的最后一步。
答案 0 :(得分:1)
第1步:创建连接检测器
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Ramana Tech Architect 2/24/2018.
*/
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager cm = (ConnectivityManager) this._context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(300);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
return false;
}
}
第2步:使用ConnectionDetector
private ConnectionDetector cd;
cd = new ConnectionDetector(getApplicationContext());
if (cd.isConnectingToInternet()) {
/// block of code
}
我用wifi和移动连接,因此在log 2次输出为真。 我在第3行断开了wifi的错误
答案 1 :(得分:1)
按照以下代码检查互联网是否可用,以及是否有效。
//I have taken dummy icon from server, so it may be removed in future. So you can place one small icon on server and then access your own URL.
<强> 1。在清单文件中指定权限,同时确保marshmellwo运行时权限句柄。因为我不会在这里显示重新获得许可。
<uses-permission android:name="android.permission.INTERNET"/>
<强> 2。检查互联网可用性以及状态是活动还是非活动。
public class InternetDemo extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkInternetAvailibility();
}
public void checkInternetAvailibility()
{
if(isInternetAvailable())
{
new IsInternetActive().execute();
}
else {
Toast.makeText(getApplicationContext(), "Internet Not Connected", Toast.LENGTH_LONG).show();
}
}
public boolean isInternetAvailable() {
try {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
} catch (Exception e) {
Log.e("isInternetAvailable:",e.toString());
return false;
}
}
class IsInternetActive extends AsyncTask<Void, Void, String>
{
InputStream is = null;
String json = "Fail";
@Override
protected String doInBackground(Void... params) {
try {
URL strUrl = new URL("http://icons.iconarchive.com/icons/designbolts/handstitch-social/24/Android-icon.png");
//Here I have taken one android small icon from server, you can put your own icon on server and access your URL, otherwise icon may removed from another server.
URLConnection connection = strUrl.openConnection();
connection.setDoOutput(true);
is = connection.getInputStream();
json = "Success";
} catch (Exception e) {
e.printStackTrace();
json = "Fail";
}
return json;
}
@Override
protected void onPostExecute(String result) {
if (result != null)
{
if(result.equals("Fail"))
{
Toast.makeText(getApplicationContext(), "Internet Not Active", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Internet Active " + result, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Internet Not Active", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPreExecute() {
Toast.makeText(getBaseContext(),"Validating Internet",Toast.LENGTH_LONG).show();
super.onPreExecute();
}
}
}
答案 2 :(得分:0)
在您的包裹上创建ProjectUtils
班级:
不要忘记添加你的Menifests
<uses-permission android:name="android.permission.INTERNET" />
ProjectUtils.java:
public class ProjectUtils {
Context context;
public ProjectUtils(Context context) {
this.context = context;
}
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
public void showtoast(String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
在活动中
ProjectUtils utils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
utils = new ProjectUtils(this);
if (utils.haveNetworkConnection()) {
jsonRequestCall();
} else {
utils.showtoast("Internet Connection Not Available");
}
}
如果您想在几秒钟内检查互联网连接那么您必须使用 BroadcastReceiver 。
参考: