Android执行网络操作

本文介绍了一种检测Android设备网络连接状态的方法,包括如何检查网络是否可用、如何在不同网络条件下下载数据以及如何根据用户偏好设置调整网络使用行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

检查网络连接

 /**
     * 检测网络是否连接
     *
     * @param context   
     * @return true :  网络连接成功   
     * @return false :  网络连接失败   
     */
    public static boolean isNetworkAvailable(Context context) {
        //  获取手机所有连接管理对象(包括对wifi,net等连接的管理)
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            //  获取网络连接管理的对象  
            NetworkInfo networkInfo = connectivityManager
                    .getActiveNetworkInfo();
            // 判断当前网络是否已经连接  
            if (networkInfo != null && networkInfo.isConnected()) {
                return true;
            }
        }
        return false;
    }

在一个单独的线程中执行网络操作

  • 网络操作会遇到不可预期的延迟。为了避免造成不好的用户体验,总是在 UI 线程之外单独的线程中执行网络操作。

连接并下载数据

  • 在执行网络交互的线程里面,我们可以使用 HttpURLConnection 来执行一个 GET 类型的操作并下载数据。在调用 connect() 之后,我们可以通过调用 getInputStream() 来得到一个包含数据的 InputStream 对象。

  • 在下面的代码示例中,doInBackground() 方法会调用 downloadUrl()。这个 downloadUrl() 方法使用给予的 URL,通过 HttpURLConnection 连接到网络。一旦建立连接后,app 就会使用 getInputStream() 来获取包含数据的 InputStream。

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
  • 请注意,getResponseCode() 会返回连接的状态码(status code)。这是一种获知额外网络连接信息的有效方式。其中,状态码是 200 则意味着连接成功。

将输入流(InputStream)转换为字符串

  • InputStream 是一种可读的 byte 数据源。如果我们获得了一个 InputStream,通常会进行解码(decode)或者转换为目标数据类型。例如,如果我们是在下载图片数据,那么可能需要像下面这样解码并展示它:
InputStream is = null;
...
Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
  • 在上面演示的示例中,InputStream 包含的是网页的文本内容。下面会演示如何把 InputStream 转换为字符串,以便显示在 UI 上。
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

检查设备的网络连接

  • 在执行网络操作之前,检查设备当前连接的网络连接信息是个好习惯。这样可以防止我们的程序在无意间连接使用了非意向的网络频道。如果网络连接不可用,那么我们的应用应该优雅地做出响应。为了检测网络连接,我们需要使用到下面两个类:

  • ConnectivityManager:它会回答关于网络连接的查询结果,并在网络连接改变时通知应用程序。

  • NetworkInfo:描述一个给定类型(就本节而言是移动网络或 Wi-Fi)的网络接口状态。
ConnectivityManager connMgr = (ConnectivityManager)
        getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
  • 请注意我们不应该仅仅靠网络是否可用来做出决策。由于 isConnected() 能够处理片状移动网络(flaky mobile networks),飞行模式和受限制的后台数据等情况,所以我们应该总是在执行网络操作前检查 isConnected()。

管理网络的使用情况

  • 我们可以实现一个偏好设置的 activity ,使用户能直接设置程序对网络资源的使用情况。例如:

  • 可以允许用户仅在连接到 Wi-Fi 时上传视频。

  • 可以根据诸如网络可用,时间间隔等条件来选择是否做同步的操作。

  • android.permission.INTERNET——允许应用程序打开网络套接字。

  • android.permission.ACCESS_NETWORK_STATE——允许应用程序访问网络连接信息。

  • 我们可以为 ACTION_MANAGE_NETWORK_USAGE action(Android 4.0中引入)声明 intent filter,表示我们的应用定义了一个提供控制数据使用情况选项的 activity。ACTION_MANAGE_NETWORK_USAGE 显示管理指定应用程序网络数据使用情况的设置。当我们的 app 有一个允许用户控制网络使用情况的设置 activity 时,我们应该为 activity 声明这个 intent filter。在章节概览提供的示例应用中,这个 action 被 SettingsActivity 类处理,它提供了偏好设置 UI 来让用户决定何时进行下载。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.networkusage"
    ...>

    <uses-sdk android:minSdkVersion="4"
           android:targetSdkVersion="14" />

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

    <application
        ...>
        ...
        <activity android:label="SettingsActivity" android:name=".SettingsActivity">
             <intent-filter>
                <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
                <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
        </activity>
    </application>
</manifest>

实现一个首选项 Activity

  • 下面是 SettingsActivity。请注意它实现了 OnSharedPreferenceChangeListener。当用户改变了他的偏好,就会触发 onSharedPreferenceChanged(),这个方法会设置 refreshDisplay 为 true(这里的变量存在于自己定义的 activity,见下一部分的代码示例)。这会使得当用户返回到 main activity 的时候进行刷新:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Loads the XML preferences file
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Registers a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

       // Unregisters the listener set in onResume().
       // It's best practice to unregister listeners when your app isn't using them to cut down on
       // unnecessary system overhead. You do this in onPause().
       getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    // When the user changes the preferences selection,
    // onSharedPreferenceChanged() restarts the main activity as a new
    // task. Sets the the refreshDisplay flag to "true" to indicate that
    // the main activity should update its display.
    // The main activity queries the PreferenceManager to get the latest settings.

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        // Sets refreshDisplay to true so that when the user returns to the main
        // activity, the display refreshes to reflect the new settings.
        NetworkActivity.refreshDisplay = true;
    }
}

响应偏好设置的改变

  • 当用户在设置界面改变了偏好,它通常都会对 app 的行为产生影响。在下面的代码示例中,app 会在 onStart() 方法中检查偏好设置。如果设置的类型与当前设备的网络连接类型相一致,那么程序就会下载数据并刷新显示。(例如, 如果设置是”Wi-Fi” 并且设备连接了 Wi-Fi)。
public class NetworkActivity extends Activity {
    public static final String WIFI = "Wi-Fi";
    public static final String ANY = "Any";
    private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";

    // Whether there is a Wi-Fi connection.
    private static boolean wifiConnected = false;
    // Whether there is a mobile connection.
    private static boolean mobileConnected = false;
    // Whether the display should be refreshed.
    public static boolean refreshDisplay = true;

    // The user's current network preference setting.
    public static String sPref = null;

    // The BroadcastReceiver that tracks network connectivity changes.
    private NetworkReceiver receiver = new NetworkReceiver();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Registers BroadcastReceiver to track network connection changes.
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkReceiver();
        this.registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Unregisters BroadcastReceiver when app is destroyed.
        if (receiver != null) {
            this.unregisterReceiver(receiver);
        }
    }

    // Refreshes the display if the network connection and the
    // pref settings allow it.

    @Override
    public void onStart () {
        super.onStart();

        // Gets the user's network preference settings
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        // Retrieves a string value for the preferences. The second parameter
        // is the default value to use if a preference value is not found.
        sPref = sharedPrefs.getString("listPref", "Wi-Fi");

        updateConnectedFlags();

        if(refreshDisplay){
            loadPage();
        }
    }

    // Checks the network connection and sets the wifiConnected and mobileConnected
    // variables accordingly.
    public void updateConnectedFlags() {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()) {
            wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
            mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        } else {
            wifiConnected = false;
            mobileConnected = false;
        }
    }

    // Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
    public void loadPage() {
        if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
                || ((sPref.equals(WIFI)) && (wifiConnected))) {
            // AsyncTask subclass
            new DownloadXmlTask().execute(URL);
        } else {
            showErrorPage();
        }
    }
...

}

检测网络连接变化

  • 最后一部分是关于 BroadcastReceiver 的子类:NetworkReceiver。 当设备网络连接改变时,NetworkReceiver 会监听到 CONNECTIVITY_ACTION,这时需要判断当前网络连接类型并相应的设置好 wifiConnected 与 mobileConnected。这样做的结果是下次用户回到 app 时,app 只会下载最新返回的结果。如果 NetworkActivity.refreshDisplay 被设置为 true,app 会更新显示。

  • 我们需要控制好 BroadcastReceiver 的使用,不必要的声明注册会浪费系统资源。示例应用在 onCreate() 中注册 BroadcastReceiver NetworkReceiver,在 onDestroy() 中销毁它。这样做会比在 manifest 里面声明 更轻巧。当我们在 manifest 里面声明一个 ,我们的程序可以在任何时候被唤醒,即使我们已经好几个星期没有运行这个程序了。而通过前面的办法注册NetworkReceiver,可以确保用户离开我们的应用之后,应用不会被唤起。如果我们确实要在 manifest 中声明 ,且确保知道何时需要使用到它,那么可以在合适的地方使用 setComponentEnabledSetting() 来开启或者关闭它。

public class NetworkReceiver extends BroadcastReceiver {   

@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager conn =  (ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = conn.getActiveNetworkInfo();

    // Checks the user prefs and the network connection. Based on the result, decides whether
    // to refresh the display or keep the current display.
    // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
    if (WIFI.equals(sPref) && networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // If device has its Wi-Fi connection, sets refreshDisplay
        // to true. This causes the display to be refreshed when the user
        // returns to the app.
        refreshDisplay = true;
        Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();

    // If the setting is ANY network and there is a network connection
    // (which by process of elimination would be mobile), sets refreshDisplay to true.
    } else if (ANY.equals(sPref) && networkInfo != null) {
        refreshDisplay = true;

    // Otherwise, the app can't download content--either because there is no network
    // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there 
    // is no Wi-Fi connection.
    // Sets refreshDisplay to false.
    } else {
        refreshDisplay = false;
        Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值