我刚刚创建了一个连接到Web服务的应用程序。但是我注意到当它在设备上时。当用户设备上没有活动的互联网时。我的应用程序崩溃,因为它无法连接到互联网网络服务。虽然在我的代码中,我已经能够检查互联网何时关闭。
所以我正在修改使用此代码来检查我是否可以在建立连接之前连接到 url。请检查设备上是否有活动数据计划的最佳方法是什么。或者我做对了。
public ValidateUrlConnection(String urlAddress){
try{
url = new URL(urlAddress);
URLConnection connection = url.openConnection();
}
catch(IOException e)
{
}
}
好吧,
您无法检查设备是否有数据计划,但是您可以使用ConnectivityManager
检查是否有活动连接
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
activeNetworkInfo.isConnected();
您可以使用此代码在调用 url 之前检查互联网连接
连接检测器.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
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)
{
Log.d("Network", "NETWORKnAME: "+info[i].getTypeName());
return true;
}
}
return false;
}}
如果没有互联网连接的邵氏警报框
警报.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertDialogManager {
@SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if (status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
然后检查互联网连接为:
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(youractivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
else
{
do_your_internet_task()
}