我刚刚创建了一个连接到webservice的应用程序。但我注意到它在设备上时。当用户设备上没有活动的互联网时。我的应用程序崩溃因为它无法连接到互联网Web服务。虽然在我的代码中,我已经能够检查互联网何时关闭。
所以我在使用此代码检查是否可以在建立连接之前连接到url。请问检查设备上是否有活动数据计划的最佳方法是什么。 或者我正在以正确的方式行事。
public ValidateUrlConnection(String urlAddress){
try{
url = new URL(urlAddress);
URLConnection connection = url.openConnection();
}
catch(IOException e)
{
}
}
答案 0 :(得分:0)
您无法检查设备是否有数据计划,但您可以使用ConnectivityManager
检查是否存在有效连接
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
activeNetworkInfo.isConnected();
答案 1 :(得分:0)
您可以在调用网址之前使用此代码检查互联网连接
Connectiondetecter.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;
}}
如果没有互联网连接,Shaow Alert框
Alert.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()
}