[英]checking network connection android
这是我检查应用程序网络连接的代码。我希望我的应用程序仅在连接到网络时运行,否则请关闭。 代码正在运行,没有错误,但是问题是多次显示Alertdialog。
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
@Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
checkCon = false;
finish();
}
}).show();
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}
以束缚回答,谢谢
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
@Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
finish();
}
}).show();
checkCon = false;
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}
在您当前的Activity
或Fragment
添加一个新方法:
private boolean isNetworkAvailable(){
boolean available = false;
/** Getting the system's connectivity service */
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
/** Getting active network interface to get the network's status */
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo !=null && networkInfo.isAvailable())
available = true;
/** Returning the status of the network */
return available;
}
这是如何使用它。 您可以在onCreate()
方法中使用它:
if (isNetworkAvailable() == true){ // if network is available
// do your thing here
...
}else{ // "else" means that the network is not available
// do your thing here
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.