修改后的示例应用程序NetworkUsage无法正常工作

时间:2013-12-30 09:54:32

标签: android networking

我正在尝试为Android构建我的第一个应用程序,首先,我在Android开发者网站上的networkusage.zip文件中编译了示例应用程序(位置:http://developer.android.com/training/basics/network-ops/index.html)。它工作正常,所以我试着根据我的目标修改它。

修改后的代码在连接到Wi-Fi网络时工作正常,但如果我将其设置为任何网络,则无法显示消息:“丢失连接。”

我只修改了“NetworkActivity.java”

public class NetworkActivity extends Activity {
    public static final String WIFI = "Wi-Fi";
    public static final String ANY = "Any";
    private static final String URL ="http://www.kibao.org/simu/wap.php?lng=";
    final Context context = this;
    // 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;

    public static String pagina = "";

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

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

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

    // 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();

    // Only loads the page if refreshDisplay is true. Otherwise, keeps previous
    // display. For example, if the user has set "Wi-Fi only" in prefs and the
    // device loses its Wi-Fi connection midway through the user using the app,
    // you don't want to refresh the display--this would force the display of
    // an error page instead of stackoverflow.com content.
    if (refreshDisplay) {
        loadPage();
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (receiver != null) {
        this.unregisterReceiver(receiver);
    }
}

// Checks the network connection and sets the wifiConnected and mobileConnected
// variables accordingly.
private 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.
// This avoids UI lock up. To prevent network operations from
// causing a delay that results in a poor user experience, always perform
// network operations on a separate thread from the UI.
private void loadPage() {
    if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
            || ((sPref.equals(WIFI)) && (wifiConnected))) {
        // AsyncTask subclass
        //new DownloadXmlTask().execute(URL);
        String lng = getResources().getString(R.string.lng);
        new DownloadWebpageTask().execute(URL.concat(lng));
    } else {
        showErrorPage();
    }
}

// Displays an error if the app is unable to load content.
private void showErrorPage() {
    setContentView(R.layout.main);

    // The specified network connection is not available. Displays error message.
    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.loadData(getResources().getString(R.string.connection_error),
            "text/html", null);
}

// Populates the activity's options menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
}

// Handles the user's menu selection.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.settings:
            Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
            startActivity(settingsActivity);
            return true;
    case R.id.refresh:
            loadPage();
            return true;
    default:
            return super.onOptionsItemSelected(item);
    }
}


// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
}

/**
 *
 * This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION,
 * which indicates a connection change. It checks whether the type is TYPE_WIFI.
 * If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the
 * main activity accordingly.
 *
 */
public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connMgr =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.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();
        }
    }
}



// Implementation of AsyncTask used to download Webpage
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        try {
            return loadWebpageFromNetwork(urls[0]);
        } catch (IOException e) {
            return getResources().getString(R.string.connection_error);
        }
    }

    @Override
    protected void onPostExecute(String result) {
        setContentView(R.layout.main);
        // Displays the HTML string in the UI via a WebView
        WebView myWebView = (WebView) findViewById(R.id.webview);
        //myWebView.loadData(result, "text/html", null);
        //myWebView.loadDataWithBaseURL("http://www.kibao.org",result, "text/html", "utf-8",null);
        String lng = getResources().getString(R.string.lng);
    myWebView.loadUrl(URL.concat(lng));            
    }
}

// Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
private String loadWebpageFromNetwork(String urlString) throws IOException {
    InputStream stream = null;
    try {
        stream = downloadUrl(urlString);
        pagina = getStringFromInputStream(stream);
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (stream != null) {
            stream.close();
        }
    }

    // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
    // Each Entry object represents a single post in the XML feed.
    // This section processes the entries list to combine each entry with HTML markup.
    // Each entry is displayed in the UI as a link that optionally includes
    // a text summary.
    return pagina;
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {

    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();

    String line;
    try {

        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();

}        

}

请帮助我理解我的错误。

非常感谢,

Nino V

1 个答案:

答案 0 :(得分:0)

我发现了自己的错误:这是一个非常愚蠢的错误!在我的arrays.xml中,我将名称和值都本地化,因此代码无法识别我的意大利语手机中的“ANY”值“Qualsiasi”!

感谢您的关注。 Nino V