连接到网络

简介: http://developer.android.youdaxue.com/training/basics/network-ops/connecting.html#securityIn order to perform network operations in your application, your manifest must include the following permissions:

http://developer.android.youdaxue.com/training/basics/network-ops/connecting.html#security


In order to perform network operations in your application, your manifest must include the following permissions:

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


public class MainActivity extends FragmentActivity implements DownloadCallback {
    ...
    // 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) {
        ...
        mNetworkFragment = NetworkFragment.getInstance(getSupportFragmentManager(), "https://www.google.com");
    }
    private void startDownload() {
        if (!mDownloading && mNetworkFragment != null) {
            // Execute the async download.
            mNetworkFragment.startDownload();
            mDownloading = true;
        }
    }
}
/**
 * Implementation of headless Fragment that runs an AsyncTask to fetch data from the network.
 */
public class NetworkFragment extends Fragment {
    public static final String TAG = "NetworkFragment";
    private static final String URL_KEY = "UrlKey";
    private DownloadCallback mCallback;
    private DownloadTask mDownloadTask;
    private String mUrlString;
    /**
     * Static initializer for NetworkFragment that sets the URL of the host it will be downloading
     * from.
     */
    public static NetworkFragment getInstance(FragmentManager fragmentManager, String url) {
        NetworkFragment networkFragment = new NetworkFragment();
        Bundle args = new Bundle();
        args.putString(URL_KEY, url);
        networkFragment.setArguments(args);
        fragmentManager.beginTransaction().add(networkFragment, TAG).commit();
        return networkFragment;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUrlString = getArguments().getString(URL_KEY);
        ...
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // Host Activity will handle callbacks from task.
        mCallback = (DownloadCallback) context;
    }
    @Override
    public void onDetach() {
        super.onDetach();
        // Clear reference to host Activity to avoid memory leak.
        mCallback = null;
    }
    @Override
    public void onDestroy() {
        // Cancel task when Fragment is destroyed.
        cancelDownload();
        super.onDestroy();
    }
    /**
     * Start non-blocking execution of DownloadTask.
     */
    public void startDownload() {
        cancelDownload();
        mDownloadTask = new DownloadTask();
        mDownloadTask.execute(mUrlString);
    }
    /**
     * Cancel (and interrupt if necessary) any ongoing DownloadTask execution.
     */
    public void cancelDownload() {
        if (mDownloadTask != null) {
            mDownloadTask.cancel(true);
        }
    }
    ...
/**
 * Implementation of AsyncTask designed to fetch data from the network.
 */
private class DownloadTask extends AsyncTask<String, Integer, DownloadTask.Result> {
    private DownloadCallback<String> mCallback;
    DownloadTask(DownloadCallback<String> callback) {
        setCallback(callback);
    }
    void setCallback(DownloadCallback<String> callback) {
        mCallback = callback;
    }
     /**
     * Wrapper class that serves as a union of a result value and an exception. When the download
     * task has completed, either the result value or exception can be a non-null value.
     * This allows you to pass exceptions to the UI thread that were thrown during doInBackground().
     */
    static class Result {
        public String mResultValue;
        public Exception mException;
        public Result(String resultValue) {
            mResultValue = resultValue;
        }
        public Result(Exception exception) {
            mException = exception;
        }
    }
    /**
     * Cancel background network operation if we do not have network connectivity.
     */
    @Override
    protected void onPreExecute() {
        if (mCallback != null) {
            NetworkInfo networkInfo = mCallback.getActiveNetworkInfo();
            if (networkInfo == null || !networkInfo.isConnected() ||
                    (networkInfo.getType() != ConnectivityManager.TYPE_WIFI
                            && networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
                // If no connectivity, cancel task and update Callback with null data.
                mCallback.updateFromDownload(null);
                cancel(true);
            }
        }
    }
    /**
     * Defines work to perform on the background thread.
     */
    @Override
    protected DownloadTask.Result doInBackground(String... urls) {
        Result result = null;
        if (!isCancelled() && urls != null && urls.length > 0) {
            String urlString = urls[0];
            try {
                URL url = new URL(urlString);
                String resultString = downloadUrl(url);
                if (resultString != null) {
                    result = new Result(resultString);
                } else {
                    throw new IOException("No response received.");
                }
            } catch(Exception e) {
                result = new Result(e);
            }
        }
        return result;
    }
    /**
     * Updates the DownloadCallback with the result.
     */
    @Override
    protected void onPostExecute(Result result) {
        if (result != null && mCallback != null) {
            if (result.mException != null) {
                mCallback.updateFromDownload(result.mException.getMessage());
            } else if (result.mResultValue != null) {
                mCallback.updateFromDownload(result.mResultValue);
            }
            mCallback.finishDownloading();
        }
    }
    /**
     * Override to add special behavior for cancelled AsyncTask.
     */
    @Override
    protected void onCancelled(Result result) {
    }
}
public interface DownloadCallback<T> {
    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(T 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();
}


目录
相关文章
|
15天前
|
运维 安全 网络架构
【专栏】NAT技术是连接私有网络与互联网的关键,缓解IPv4地址短缺,增强安全性和管理性
【4月更文挑战第28天】NAT技术是连接私有网络与互联网的关键,缓解IPv4地址短缺,增强安全性和管理性。本文阐述了五大NAT类型:全锥形NAT(安全低,利于P2P)、限制锥形NAT(增加安全性)、端口限制锥形NAT(更安全,可能影响协议)、对称NAT(高安全,可能导致兼容性问题)和动态NAT(公网IP有限时适用)。选择NAT类型需考虑安全性、通信模式、IP地址数量和设备兼容性,以确保网络高效、安全运行。
|
16天前
|
安全 网络协议 物联网
城域以太网:连接城市的高速网络
【4月更文挑战第22天】
22 0
|
17天前
|
数据可视化 网络协议
|
17天前
|
设计模式 数据中心 网络架构
|
25天前
|
安全 网络安全 数据安全/隐私保护
HTTP代理SSL连接:保障网络安全的重要协议
HTTP代理SSL连接:保障网络安全的重要协议
|
27天前
|
运维 安全 Cloud Native
安全访问服务边缘(SASE):网络新时代的安全与连接解决方案
SASE(安全访问服务边缘)是一种云基安全模型,结合了网络功能和安全策略,由Gartner在2019年提出。它强调身份驱动的私有网络、云原生架构和全面边缘支持,旨在解决传统WAN和安全方案的局限性,如高延迟和分散管理。SASE通过降低IT成本、提升安全响应和网络性能,应对数据分散、风险控制和访问速度等问题,适用于移动办公、多分支办公等场景。随着网络安全挑战的增加,SASE将在企业的数字化转型中扮演关键角色。
|
1月前
|
算法 测试技术 C#
【树上倍增】【割点】 【换根法】3067. 在带权树网络中统计可连接服务器对数目(三)
【树上倍增】【割点】 【换根法】3067. 在带权树网络中统计可连接服务器对数目
【树上倍增】【割点】 【换根法】3067. 在带权树网络中统计可连接服务器对数目(二)
【树上倍增】【割点】 【换根法】3067. 在带权树网络中统计可连接服务器对数目
|
1月前
|
人工智能 BI 测试技术
【树上倍增】【割点】 【换根法】3067. 在带权树网络中统计可连接服务器对数目(一)
【树上倍增】【割点】 【换根法】3067. 在带权树网络中统计可连接服务器对数目
|
1月前
|
Ubuntu 网络协议 Windows
ubuntu 16.04无法连接网络;双系统无法上网;连接已断开,你现在处于断开状态
ubuntu 16.04无法连接网络;双系统无法上网;连接已断开,你现在处于断开状态