Android开发培训(10)--app网络连接

xiaoxiao2021-02-28  114

这篇文章教你如何进行网络链接,你会学习连接其它的设备,连接到网络,连接到云,以及同步你的app数据,还有其它的更多。

第一章 建立无线连接

第二章 网络连接操作

第三章 传递数据

第四章 使用同步适配器进行传递数据

第五章 使用Volley传递数据

第一章 建立无线连接

通过自己的app与周围的设备进行连接,p2p, Nearby Connections API.

第一节 注册你的设备服务

这个可以让别的设备连接上你的服务

有需要再学习,这个无线连接仅限于本地的局域网,作用范围有限,等有需要再学习相关文档。

第二章 网络操作

为了使用网络连接,app的manifest文件中必须包括这两个权限

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 第一节 建立安全的网络连接

在你为你的app添加网络功能之前,你需要保证你app里面的数据在进行网络传输的时候是安全的。下面的是基本的网络安全的建议:

最小化你可以通过网络传输的数据,就是能不传尽量不传。

通过ssl进行数据传输。

创建一个网络安全确认机制。

第二节 选择一个http客户端

很多网络连接都是通过http进行收发数据,android平台包括HttpURLConnection客户端,它支持TLS,流的上传和下载,配置超时时间,以及IPv6,和连接池。

第三节 创建一个独立的线程处理网络连接

为了避免网络部分block主了主UI,所以不要在主UI中进行网络操作,android 3.0以后强制这样做,否则会报出NetworkOnMainThreadException错误。

下面的Activity片段使用一个Fragment进行异步网络操作。后面你可以看到Fragment是如何实现的。你的Activity也需要实现DownloadCallback接口,这个接口允许fragment对Activity进行回调,比如这个它需要连接状态,需要将更新送到UI主线程中。

编写DownloadCallback接口

写得太好,自愧不如,后面的例子中需要应用,背后下载,如何实现。

/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.networkconnect; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; /** * Sample Activity demonstrating how to connect to the network and fetch raw * HTML. It uses a Fragment that encapsulates the network operations on an AsyncTask. * * This sample uses a TextView to display output. */ public class MainActivity extends FragmentActivity implements DownloadCallback { // Reference to the TextView showing fetched data, so we can clear it with a button // as necessary. private TextView mDataText; // Keep a reference to the NetworkFragment which owns the AsyncTask object // that is used to execute network ops. private NetworkFragment mNetworkFragment; // Boolean telling us whether a download is in progress, so we don't trigger overlapping // downloads with consecutive button clicks. private boolean mDownloading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sample_main); mDataText = (TextView) findViewById(R.id.data_text); mNetworkFragment = NetworkFragment.getInstance(getSupportFragmentManager(), "https://www.baidu.com/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // When the user clicks FETCH, fetch the first 500 characters of // raw HTML from www.google.com. case R.id.fetch_action: startDownload(); return true; // Clear the text and cancel download. case R.id.clear_action: finishDownloading(); mDataText.setText(""); return true; } return false; } private void startDownload() { if (!mDownloading && mNetworkFragment != null) { // Execute the async download. mNetworkFragment.startDownload(); mDownloading = true; } } @Override public void updateFromDownload(String result) { if (result != null) { mDataText.setText(result); } else { mDataText.setText(getString(R.string.connection_error)); } } @Override public NetworkInfo getActiveNetworkInfo() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo; } @Override public void finishDownloading() { mDownloading = false; if (mNetworkFragment != null) { mNetworkFragment.cancelDownload(); } } @Override public void onProgressUpdate(int progressCode, int percentComplete) { switch(progressCode) { // You can add UI behavior for progress updates here. case Progress.ERROR: break; case Progress.CONNECT_SUCCESS: break; case Progress.GET_INPUT_STREAM_SUCCESS: break; case Progress.PROCESS_INPUT_STREAM_IN_PROGRESS: mDataText.setText("" + percentComplete + "%"); break; case Progress.PROCESS_INPUT_STREAM_SUCCESS: break; } } } /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.networkconnect; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; /** * Sample Activity demonstrating how to connect to the network and fetch raw * HTML. It uses a Fragment that encapsulates the network operations on an AsyncTask. * * This sample uses a TextView to display output. */ public class MainActivity extends FragmentActivity implements DownloadCallback { // Reference to the TextView showing fetched data, so we can clear it with a button // as necessary. private TextView mDataText; // Keep a reference to the NetworkFragment which owns the AsyncTask object // that is used to execute network ops. private NetworkFragment mNetworkFragment; // Boolean telling us whether a download is in progress, so we don't trigger overlapping // downloads with consecutive button clicks. private boolean mDownloading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sample_main); mDataText = (TextView) findViewById(R.id.data_text); mNetworkFragment = NetworkFragment.getInstance(getSupportFragmentManager(), "https://www.baidu.com/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // When the user clicks FETCH, fetch the first 500 characters of // raw HTML from www.google.com. case R.id.fetch_action: startDownload(); return true; // Clear the text and cancel download. case R.id.clear_action: finishDownloading(); mDataText.setText(""); return true; } return false; } private void startDownload() { if (!mDownloading && mNetworkFragment != null) { // Execute the async download. mNetworkFragment.startDownload(); mDownloading = true; } } @Override public void updateFromDownload(String result) { if (result != null) { mDataText.setText(result); } else { mDataText.setText(getString(R.string.connection_error)); } } @Override public NetworkInfo getActiveNetworkInfo() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo; } @Override public void finishDownloading() { mDownloading = false; if (mNetworkFragment != null) { mNetworkFragment.cancelDownload(); } } @Override public void onProgressUpdate(int progressCode, int percentComplete) { switch(progressCode) { // You can add UI behavior for progress updates here. case Progress.ERROR: break; case Progress.CONNECT_SUCCESS: break; case Progress.GET_INPUT_STREAM_SUCCESS: break; case Progress.PROCESS_INPUT_STREAM_IN_PROGRESS: mDataText.setText("" + percentComplete + "%"); break; case Progress.PROCESS_INPUT_STREAM_SUCCESS: break; } } } /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.networkconnect; import android.net.NetworkInfo; import android.support.annotation.IntDef; /** * Sample interface containing bare minimum methods needed for an asynchronous task * to update the UI Context. */ public interface DownloadCallback { interface Progress { int ERROR = -1; int CONNECT_SUCCESS = 0; int GET_INPUT_STREAM_SUCCESS = 1; int PROCESS_INPUT_STREAM_IN_PROGRESS = 2; int PROCESS_INPUT_STREAM_SUCCESS = 3; } /** * Indicates that the callback handler needs to update its appearance or information based on * the result of the task. Expected to be called from the main thread. */ void updateFromDownload(String result); /** * Get the device's active network status in the form of a NetworkInfo object. */ NetworkInfo getActiveNetworkInfo(); /** * Indicate to callback handler any progress update. * @param progressCode must be one of the constants defined in DownloadCallback.Progress. * @param percentComplete must be 0-100. */ void onProgressUpdate(int progressCode, int percentComplete); /** * Indicates that the download operation has finished. This method is called even if the * download hasn't completed successfully. */ void finishDownloading(); } 主线程后分线程,写得分开,不会block主线程。

转载请注明原文地址: https://www.6miu.com/read-48341.html

最新回复(0)