📅  最后修改于: 2021-01-05 05:24:51             🧑  作者: Mango
Android使您的应用程序连接到Internet或任何其他本地网络,并允许您执行网络操作。
设备可以具有各种类型的网络连接。本章重点介绍使用Wi-Fi或移动网络连接。
在执行任何网络操作之前,必须首先检查是否已连接到该网络或Internet等。为此android提供ConnectivityManager类。您需要通过调用getSystemService()方法来实例化此类的对象。其语法如下-
ConnectivityManager check = (ConnectivityManager)
this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
实例化ConnectivityManager类的对象后,就可以使用getAllNetworkInfo方法获取所有网络的信息。此方法返回NetworkInfo数组。因此,您必须像这样接收它。
NetworkInfo[] info = check.getAllNetworkInfo();
您需要做的最后一件事是检查网络的连接状态。其语法如下-
for (int i = 0; i
除了这些连接状态之外,网络还可以实现其他状态。它们在下面列出-
Sr.No | State |
---|---|
1 | Connecting |
2 | Disconnected |
3 | Disconnecting |
4 | Suspended |
5 | Unknown |
检查您已连接到Internet后,您可以执行任何网络操作。在这里,我们从网址中获取网站的html。
Android提供HttpURLConnection和URL类来处理这些操作。您需要通过提供网站链接来实例化URL类的对象。它的语法如下-
String link = "http://www.google.com";
URL url = new URL(link);
之后,您需要调用url类的openConnection方法并将其接收到HttpURLConnection对象中。之后,您需要调用HttpURLConnection类的connect方法。
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
最后,您需要做的就是从网站获取HTML。为此,您将使用InputStream和BufferedReader类。其语法如下-
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";
while ((data = reader.readLine()) != null){
webPage += data + "\n";
}
除了此connect方法之外,HttpURLConnection类中还有其他可用的方法。它们在下面列出-
Sr.No | Method & description |
---|---|
1 |
disconnect() This method releases this connection so that its resources may be either reused or closed |
2 |
getRequestMethod() This method returns the request method which will be used to make the request to the remote HTTP server |
3 |
getResponseCode() This method returns response code returned by the remote HTTP server |
4 |
setRequestMethod(String method) This method Sets the request command which will be sent to the remote HTTP server |
5 |
usingProxy() This method returns whether this connection uses a proxy server or not |
下面的示例演示HttpURLConnection类的用法。它创建一个基本的应用程序,使您可以从给定的网页下载HTML。
要尝试使用此示例,您需要在连接了wifi互联网的实际设备上运行该示例。
Steps | Description |
---|---|
1 | You will use Android studio IDE to create an Android application under a package com.tutorialspoint.myapplication. |
2 | Modify src/MainActivity.java file to add Activity code. |
4 | Modify layout XML file res/layout/activity_main.xml add any GUI component if required. |
6 | Modify AndroidManifest.xml to add necessary permissions. |
7 | Run the application and choose a running android device and install the application on it and verify the results. |
这是src / MainActivity.java的内容。
package com.tutorialspoint.myapplication;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends ActionBarActivity {
private ProgressDialog progressDialog;
private Bitmap bitmap = null;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkInternetConenction();
downloadImage("http://www.tutorialspoint.com/green/images/logo.png");
}
});
}
private void downloadImage(String urlStr) {
progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
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();
}
private InputStream openHttpConnection(String urlStr) {
InputStream in = null;
int resCode = -1;
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return in;
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
progressDialog.dismiss();
}
};
private boolean checkInternetConenction() {
// get Connectivity Manager object to check connection
ConnectivityManager connec
=(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connections
if ( connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() ==
android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
return true;
}else if (
connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() ==
android.net.NetworkInfo.State.DISCONNECTED ) {
Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
return false;
}
return false;
}
}
这是activity_main.xml的内容。
这是Strings.xml的内容。
My Application
这是AndroidManifest.xml的内容
让我们尝试运行您的应用程序。我假设您已将实际的Android Mobile设备与计算机连接。要从android studio运行该应用,请打开您项目的活动文件之一,然后点击运行工具栏中的图标。在启动应用程序之前,Android Studio将显示以下窗口,以选择要在其中运行Android应用程序的选项。
选择您的移动设备作为选项,然后检查将显示以下屏幕的移动设备-
现在只需单击按钮,它将检查互联网连接以及下载图像。
出来如下,它已经从互联网上获取了徽标。