我在Android世界中很新,我正在开发一个应用程序,但我无法建立任何互联网连接(或者即使我尝试发送电子邮件)连接和wifi。一切正常,直到(例如):
之类的命令HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect(); // here it fails
OR
InetAddress indirizzo = InetAddress.getByName("www.websitename.com"); // here it fails
OR
FTPClient ftpClient = new FTPClient();
ftpClient.connect("xxx.xxx.xxx.xxx",21); // here it fails
我已经尝试了很多我在不同教程中找到的解决方案:代码在我的PC上在java应用程序中正常工作,但相同的代码在我的智能手机和AVD上都不起作用。我已经在清单文件中使用了所有必需的权限:
"android.permission.INTERNET"
"android.permission.ACCESS_NETWORK_STATE"
但我认为缺少某些东西。有人能帮帮我吗?谢谢!
答案 0 :(得分:0)
首先检查您的设备是否有互联网连接: -
public static boolean CheckInternet(Context context)
{
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return wifi.isConnected() || mobile.isConnected();
}
阅读以下文档: -
http://developer.android.com/reference/java/net/HttpURLConnection.html
http://developer.android.com/reference/java/net/URLConnection.html
private void downloadImage(String urlStr) {
progressDialog = ProgressDialog.show(this, "", "Fetching Image...");
final String url = urlStr;
new Thread() {
public void run() {
InputStream in = null;
Message msg = Message.obtain();
msg.what = 1;
try {
in = openHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
messageHandler.sendMessage(msg);
}
}.start();
}