检查是否有 ACTIVE Internet 连接 [英] Checking if there is an ACTIVE Internet Connection
问题描述
我一直在忙于 Android 开发,并且在尝试检查是否有 ACTIVE Internet 连接时遇到了一些麻烦,即使网络已打开.
I am have been fiddling with Android development and I have been having some trouble trying to check if there is an ACTIVE Internet connection even if the net is ON.
因为有时即使您已连接到 WIFI 或 DATA,有时也无法连接.
Since sometimes even though you are connected to the WIFI or DATA there are times there would be no connection.
每次我点击按钮时,我的应用程序都会崩溃.我对布尔方法还是个菜鸟.
Every time I click the button my app crashes. I am still a noob regarding boolean methods.
提前感谢您的任何帮助,如果你们想到任何更好的方法我可以解决这个问题,我将不胜感激 :D
Thanks for any help in advance and if you guys think of any better ways I could approach this I would be grateful :D
这是我的主要活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCheck = (Button) findViewById(R.id.btnCheck);
btnCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isInternetAvailable()){
Toast.makeText(MainActivity.this, "There is a connection", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "NO connection", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isInternetAvailable() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 80);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) { return false; }
}
推荐答案
试试下面的代码
Boolean isInternetPresent = false;
ConnectionDetector cd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCheck = (Button) findViewById(R.id.btnCheck);
btnCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
Toast.makeText(MainActivity.this, "There is a connection", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "NO connection", Toast.LENGTH_SHORT).show();
}
}
});
}
也不要忘记在清单文件中添加互联网权限.
also don't forget to add internet permission in manifest file.
这篇关于检查是否有 ACTIVE Internet 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!