Android网络技术

Android网络技术

查看当前网络连接

首先要得到ConnectivityManager对象,然后调用getActiveNetworkInfo()方法,返回一个NetworkInfo对象。

ConnectivityManager manager= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info=manager.getActiveNetworkInfo();

注意:查看网络连接要声明权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

WebView的用法

WebView通常用于在应用程序中展示一些网页,而不是用浏览器去加载和显示,借助WebView我们可以在应用程序中嵌入一个浏览器,从而展示各种各样的网页。
首先要在布局中加入一个WebView

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></WebView>

然后使用findViewById()方法得到WebView的实例,然后调用getSettin()方法可以去设置一些浏览器的属性,这里只调用setJavaScriptEnabled()方法来让WebView支持JavaScript脚本。接着调用setWebViewClient()方法,并传入WebViewClient的匿名类作为参数,重写几个方法。最后调用WebView的loadUrl()方法,并传入网址即可。
最后,别忘了因为要访问网络,要声明访问网络的权限。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

综合示例

这里点击按钮,用一个TextView显示当前网络连接类型。在下边用一个帧布局,展示一个WebView,加载时用progressBar显示加载进度。如果加载错误,显示自定义错误!
首先是布局xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取网络连接"/>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></WebView>
        <TextView
            android:id="@+id/textview_error"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:gravity="center" />
        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:id="@+id/progressbar"
            android:visibility="invisible"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </FrameLayout>
</LinearLayout>

MainActivity.java

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private TextView textView;
    private TextView textView_error;
    private ConnectivityManager manager;
    private WebView webview;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        textView= (TextView) findViewById(R.id.textview);
        textView_error= (TextView) findViewById(R.id.textview_error);
        webview= (WebView) findViewById(R.id.webview);
        progressBar= (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面加载开始
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {//页面加载结束
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {//页面加载错误
                super.onReceivedError(view, errorCode, description, failingUrl);
                webview.setVisibility(View.GONE);
                textView_error.setVisibility(View.VISIBLE);
                textView_error.setText("加载失败");
            }
        });

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {//当前页面加载进度
                super.onProgressChanged(view, newProgress);
                progressBar.setProgress(newProgress);
            }
        });
        webview.loadUrl("http://www.baidu.com");
        Button button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NetworkInfo info=manager.getActiveNetworkInfo();
                if (info!=null&&info.isConnected()){
                    Toast.makeText(getApplicationContext(), "有网络连接", Toast.LENGTH_SHORT).show();
                    textView.setText(info.getTypeName());
                }else{
                    Toast.makeText(getApplicationContext(), "无网络连接", Toast.LENGTH_SHORT).show();
                    textView.setText("无网络连接");
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if(webview.canGoBack()){
            webview.goBack();//点击返回按钮,返回上一个WebView界面
        }else {
            finish();
        }
    }
}

访问网络

在Android上发送HTTP请求的方式一般有两种,HttpURLConnection和HttpClient。

HttpURLConnection/URLConnection

注意: URLConnection和HttpURLConnection使用的都是java.net中的类,属于标准的java接口。HttpURLConnection继承自URLConnection,差别在与HttpURLConnection仅仅针对Http连接。
首先我们在布局中放一个按钮,点击请求一个页面,然后用一个TextView展示返回的内容。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="连接服务器"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/textview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {
    private static final int CONECT_SERVLET=0x23;
    private TextView textView;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch (msg.what){
               case CONECT_SERVLET:
                   String content= (String) msg.obj;
                   textView.setText(content);
                   break;
               default:
                   break;
           }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView= (TextView) findViewById(R.id.textview);
        Button button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {//不能在主线程中连接网络,所有另开启线程
                    @Override
                    public void run() {
                        conectServlet();
                    }
                }).start();
            }
        });
    }
    private void conectServlet() {
        try {
            //自己搭建的Tomcat服务器
            URL url=new URL("http://192.168.0.56:8080/MyTomcat/hello.html");
            //URL url=new URL("http://www.360.com");访问360网站
            URLConnection connection=url.openConnection();
            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line=br.readLine();
            StringBuffer buffer=new StringBuffer();
            while (line!=null){
                buffer.append(line);
                line=br.readLine();
            }
            Message message=handler.obtainMessage();
            message.what=CONECT_SERVLET;
            message.obj=buffer.toString();
            handler.sendMessage(message);
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务器返回的是网页的HTML代码

HttpClient

HttpClient是Apache提供的HTTP网络访问接口,从一开始的时候就被引入到了Android API中。(但是在Android6.0中删除了相关API,被OKHttp代替!)
使用步骤:
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接。
具体的代码示例,就不再写了,在前边的博客中也写了具体的用法。

访问网络下载文件

这里在布局中放入两个按钮,一个为单线程下载,一个为多线程下载。最上边放在一个progressBar显示当前下载的进度

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ProgressBar
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button_single"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="单线程下载"/>
    <Button
        android:id="@+id/button_multi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="多线程下载"/>
</LinearLayout>

然后创建一个多线程下载的类MultiThread继承Thread

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2015/9/13.
 */
public class MultiThread extends Thread {
    private int sum;
    private long start;
    private long end;
    private String urlPath;//下载服务器地址
    private String filePath;//下载文件存放路径

    public MultiThread( long start,long end, String urlPath,String filePath) {
        this.end = end;
        this.filePath = filePath;
        this.start = start;
        this.urlPath = urlPath;
    }

    public int getSum() {
        return sum;
    }

    @Override
    public void run() {
        try {
            URL url=new URL(urlPath);
            URLConnection connection=url.openConnection();
            connection.setAllowUserInteraction(true);
            connection.setRequestProperty("Range","bytes="+start+"-"+end);
            InputStream is=connection.getInputStream();
            byte[] array=new byte[1024];
            File file=new File(filePath);
            RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw");//随机读写文件
            randomAccessFile.seek(start);
            int index = is.read(array);
            while (index!=-1){
                randomAccessFile.write(array,0,index);
                sum=sum+index;
                index=is.read(array);
            }
            randomAccessFile.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这里用到RandomAccessFile类,用于随机读写文件,首先生产RandomAccessFile对象,然后调用seek()方法,用来控制访问开始的位置。

MainActivity.java

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {
    private ProgressBar progressbar;
    private int length;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x23:
                    progressbar.setProgress((int) (msg.arg1*100.0/length));
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressbar= (ProgressBar) findViewById(R.id.progressbar);
        Button button_single= (Button) findViewById(R.id.button_single);
        button_single.setOnClickListener(new View.OnClickListener() {//单线程下载
            @Override
            public void onClick(View v) {
                new DownloadTask().execute();
            }
        });
        Button button_multi= (Button) findViewById(R.id.button_multi);
        button_multi.setOnClickListener(new View.OnClickListener() {//多线程下载
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //String urlPath="http://192.168.0.30:8080/MyWebTest/music/aa.mp3";
                        String urlPath="http://192.168.0.56:8080/MyTomcat/AhYeah.mp3";
                        try {
                            URL url=new URL(urlPath);
                            URLConnection connection=url.openConnection();
                            length=connection.getContentLength();
                            File file=new File(Environment.getExternalStorageDirectory(),"AhYeah.mp3");
                            if (!file.exists()){
                                file.createNewFile();
                            }
                            MultiThread[] threads=new MultiThread[5];//这里开启5个线程下载
                            for (int i=0;i<5;i++){
                                MultiThread thread=null;
                                if (i==4){
                                    thread=new MultiThread(length/5*4,length,urlPath,file.getAbsolutePath());
                                }else {
                                    thread=new MultiThread(length/5*i,length/5*(i+1)-1,urlPath,file.getAbsolutePath());
                                }
                                thread.start();
                                threads[i]=thread;
                            }
                            boolean isFinish=true;
                            while (isFinish){
                                int sum=0;
                                for (MultiThread thread:threads){
                                    sum=sum+thread.getSum();
                                }
                                Message message=handler.obtainMessage();
                                message.what=0x23;
                                message.arg1=sum;
                                handler.sendMessage(message);
                                if (sum>=length){
                                    isFinish=false;
                                }
                                Thread.sleep(1000);
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
    class DownloadTask extends AsyncTask<String,Integer,String>{

        @Override
        protected String doInBackground(String... params) {
            try {
                //访问下载搭建的服务器下的图片
                URL url=new URL("http://192.168.0.56:8080/MyTomcat/weheartit.png");
                URLConnection connection=url.openConnection();
                int length=connection.getContentLength();
                File file=new File(Environment.getExternalStorageDirectory(),"weheartit.png");
                if(!file.exists()){
                    file.createNewFile();
                }
                InputStream is=connection.getInputStream();
                OutputStream os=new FileOutputStream(file);
                byte[] array=new byte[1024];
                int sum=0;
                int index=is.read(array);
                while (index!=-1){
                    os.write(array,0,index);
                    sum=sum+index;
                    publishProgress(sum,length);
                    index=is.read(array);
                }
                os.flush();
                os.close();
                is.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "您好,文件已下载完成";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressbar.setProgress((int)(values[0]*100.0/values[1]));
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
        }
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值