安卓之網絡連接

【目錄】

怎樣連接網絡?
連接後臺服務器
單線程文件下載
多線程文件下載

1、怎麼連接網絡(wifi,流量)

佈局文件

<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/network_detail"
        android:layout_width="match_parent"
        android:layout_height="30dp" />
    <Button
        android:id="@+id/button_getNetDetail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="獲得網絡連接狀態" />

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:id="@+id/progressbar"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:visibility="invisible"/>
    <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>//webview用來顯示網頁的內容
        <TextView
            android:id="@+id/textview_error"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"
            android:text="網絡連接錯誤"/>
    </FrameLayout>

這裏寫圖片描述

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView mTextView;
    private Button mButton;
    private ConnectivityManager mConnectivityManager;//生命變量網絡連接管理器
    private WebView mWebView;
    private TextView mTextViewError;
    private ProgressBar mProgressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.network_detail);
        mButton = (Button) findViewById(R.id.button_getNetDetail);
        mTextViewError = (TextView) findViewById(R.id.textview_error);
        mProgressbar = (ProgressBar) findViewById(R.id.progressbar);
        mButton.setOnClickListener(this);
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);//網絡連接管理器

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);  // 啓用JavaScript
//下面幾行用來實現放大縮小頁面
        mWebView.getSettings().setSupportZoom(true);//縮放開關設置此屬性,
        // 僅支持雙擊縮放,不支持觸摸縮放(在android4.0是這樣,其他平臺沒試過)
        mWebView.getSettings().setBuiltInZoomControls(true);// 設置是否可縮放
        mWebView.getSettings().setUseWideViewPort(true);//無限縮放

        mWebView.setWebChromeClient(new WebChromeClient() {
        //在這個方法中重寫以下方法,實現進度條,連接出錯的設置
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mProgressbar.setProgress(newProgress);
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mProgressbar.setVisibility(view.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mProgressbar.setVisibility(view.INVISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                mWebView.setVisibility(view.GONE);
                Toast.makeText(getApplicationContext(), "同步失敗,稍後重試", Toast.LENGTH_SHORT).show();
                ;
                mTextViewError.setText("加載失敗");
                mTextViewError.setVisibility(view.VISIBLE);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       if(keyCode==KeyEvent.KEYCODE_BACK){
           if(mWebView.canGoBack()){
               mWebView.goBack();
               return  true;
           }else {
               MainActivity.this.finish();
           }
       }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.button_getNetDetail:
                mWebView.loadUrl("http://www.baidu.com");//瀏覽百度
             NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();//得到網絡連接的狀態
                if(info!=null&&info.isConnected()){
                    Toast.makeText(MainActivity.this,"有網絡連接",Toast.LENGTH_SHORT).show();
                    mTextView.setText("網絡連接狀態爲"+info.getTypeName());
                }else{
                    Toast.makeText(MainActivity.this,"無網絡連接",Toast.LENGTH_SHORT).show();
                    mTextView.setText("網絡斷開連接");
                }
                break;
        }
    }
}

2、連接後臺服務器

public class NetworkActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mButton;
    private  Button mButtonDownload;
    private TextView mTextView;
    private Handler handler= new Handler(){//得到發送來的信息
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String content = (String) msg.obj;
                    mTextView.setText(content);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network);
        mTextView = (TextView) findViewById(R.id.textview);
        mButton = (Button) findViewById(R.id.button_net);
        mButton.setOnClickListener(this);
        mButtonDownload = (Button) findViewById(R.id.button_download);
        mButtonDownload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_net:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        connectionServerlet();//調用連接服務方法,如下
                    }
                }).start();//定義新的線程並啓動
                break;
            case R.id.button_download://點擊下載按鈕時啓動DownLoadActivity
                Intent intent = new Intent(NetworkActivity.this,DownLoadActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void connectionServerlet() {
        try {
            URL url = new URL("http://192.168.0.30:8080/MyWebTest/MyTestServerlet");//定義url,得到服務器後臺的ip地址
         URLConnection connection = url.openConnection();//打開url連接
//下面讀url的內容
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            StringBuffer buffer = new StringBuffer();
            while (line != null) {
                Log.d("", line);
                buffer.append(line);//將讀到的內容加到字符串buffer中
                line = br.readLine();
            }
            Message msg = handler.obtainMessage();
            msg.what = 0;//0是自定義的一個值,與上面得到的what值對應
            msg.obj = buffer.toString().trim();
            handler.sendMessage(msg);//調用方法,發送信息
            br.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、文件下載(單線程,多線程)

單線程

佈局文件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ProgressBar
            android:id="@+id/progressbar"
            style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/button_single"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="單線程下載" />

        <Button
            android:id="@+id/button_more"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="多線程下載" />
    </LinearLayout>
</ScrollView>
  • 關於ScrollView
    一種可供用戶滾動的層次結構佈局容器,允許顯示比實際多的內容。ScrollView是一種FrameLayout,意味需要在其上放置有自己滾動內容的子元素。子元素可以是一個複雜的對象的佈局管理器。通常用的子元素是垂直方向的LinearLayout,顯示在最上層的垂直方向可以讓用戶滾動的箭頭。 只允許有一個子元素。

DownloadActivity

public class DownLoadActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mButtonSingle;
    private Button mButtonMore;
    private ProgressBar mProgressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        mButtonSingle = (Button) findViewById(R.id.button_single);
        mButtonMore = (Button) findViewById(R.id.button_more);
        mProgressbar = (ProgressBar) findViewById(R.id.progressbar);
        mButtonSingle.setOnClickListener(this);
        mButtonMore.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_single:
                SingleDownloadTask task = new SingleDownloadTask();//單線程下載
                task.execute();
                break;
            case  R.id.button_more:
                break;
            default:
                break;
        }
    }

    class SingleDownloadTask extends AsyncTask<String,Integer,String>{//繼承AsyncTask,重寫 doInBackground方法
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgressbar.setProgress((int)(values[0]*100.0/values[1]));
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3");//得到下載文件的地址
                URLConnection connection = url.openConnection();
                int length = connection.getContentLength();
                InputStream is = connection.getInputStream();//讀
                File file = new File(Environment.getExternalStorageDirectory(),"aa.mp3");//在sdcard中找到一個文件用來存放下載下來的內容
                if(!file.exists()){
                    file.createNewFile();//如果沒找到,新建一個文件
                }
                FileOutputStream 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+=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 null;
        }
    }
}


多線程

要寫一個MulityThread

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

    private int sum = 0;
    private long start;
    private long end;
    private String urlPath;
    private String filePath;

    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];
            is.read(array);
            File file = new File(filePath);
            RandomAccessFile randomAccessFileile = new RandomAccessFile(file, "rw");
            randomAccessFileile.seek(start);
            int index = is.read(array);
            while (index != -1) {
                randomAccessFileile.write(array, 0, index);
                sum += index;
                index = is.read(array);
            }
            randomAccessFileile.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 case R.id.button_more:
                //多線程下載,activity中的點擊事件

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String urlPath = "http://192.168.0.30:8080/MyWebTest/music/aa.mp3";
                            URL url = new URL(urlPath);
                            URLConnection connection = url.openConnection();
                            length = connection.getContentLength();//得到文件的總長度
                            File file = new File(Environment.getExternalStorageDirectory(), "cc.mp3");
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            MultiThread[] threads = new MultiThread[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 += thread.getSum();
                                }
                                Message msg = handler.obtainMessage();
                                msg.what = 0x23;
                                msg.arg1 = sum;
                                handler.sendMessage(msg);
                                if (sum + 10 >= length) {
                                    isFinish = false;
                                }
                                Thread.sleep(1000);
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
                break;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章