1

我开始使用来自http://developer.android.com的材料在 android 中进行开发。

我采用了他们的一个示例并对其进行了修改,以便我的应用程序可以连接到网页。它在打开时运行良好,但是如果我单击应该打开另一个页面的 actionBar 项目,则新页面不会在 WebView 中打开,而是启动了默认浏览器。

我尝试了多种方式来了解如何避免这种情况,但我的经验并不能让我解决这个问题。

你能帮助我吗?

非常感谢。尼诺

public class MainActivity extends Activity {
    public static final String WIFI = "Wi-Fi";
    public static final String ANY = "Any";
    public static String PAGINA ="http://www.kibao.org/simu/wap.php?lng=";    
    public static String BASE ="http://www.kibao.org";
    public static String ATTUALE ="";
    public static String lng = "";
    final Context context = this;

    private static boolean wifiConnected = false;
    private static boolean mobileConnected = false;
    public static boolean refreshDisplay = true;
    public static String sPref = null;

    public static String pagina = "";

    private NetworkReceiver receiver = new NetworkReceiver();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        lng = getResources().getString(R.string.lng);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkReceiver();
        this.registerReceiver(receiver, filter);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

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

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        sPref = sharedPrefs.getString("listPref", "Wi-Fi");

        updateConnectedFlags();


        if (refreshDisplay) {
            ATTUALE=PAGINA.concat(lng);
            loadPage(ATTUALE);
        }
    }
    @Override
    public void onDestroy() {
        super.onStop();
        String ciao = getResources().getString(R.string.ciao);
        show_toast(ciao);
        if (receiver != null) {
           this.unregisterReceiver(receiver);
        }
    }
    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;
        }
    }

    private void loadPage(String pgUrl) {
        if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
            || ((sPref.equals(WIFI)) && (wifiConnected))) {
            new DownloadWebpageTask().execute(pgUrl);
        } else {
            showErrorPage();
        }
    }

   // Displays an error if the app is unable to load content.
   private void showErrorPage() {
        .... 
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.items, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menu1:
        if (refreshDisplay) {

            ATTUALE=BASE.concat("/partite.php?lng=");
            ATTUALE=ATTUALE.concat(lng);
            loadPage(ATTUALE);
        }
        return true;
    ....
    default:
        return super.onOptionsItemSelected(item);
    }

    }
    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);
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
   }

    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();
            if (WIFI.equals(sPref) && networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                refreshDisplay = true;
                Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
            } else if (ANY.equals(sPref) && networkInfo != null) {
                refreshDisplay = true;
            } else {
                refreshDisplay = false;
                Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
            }
        }
    }

    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);
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.loadUrl(ATTUALE);            
        }
    }
    private String loadWebpageFromNetwork(String urlString) throws IOException {
        InputStream stream = null;
        try {
            stream = downloadUrl(urlString);
            pagina = getStringFromInputStream(stream);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    return pagina;
    }
    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();

}        
........
}
4

2 回答 2

0

我找到了另一种可行的解决方案。我添加了行

 myWebView.setWebViewClient(new WebViewClient()); 

在 onPostExecute 中:

protected void onPostExecute(String result) {
        setContentView(R.layout.main);
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.loadUrl(ATTUALE);            
}

谢谢,弗兰克。

PS 我已经尝试在弗兰克的最后一篇文章中添加评论,但我没有成功!

于 2013-08-27T06:04:00.677 回答
0

此 DownloadWebpageTask 尝试使用 webview 将网页“下载”到字符串中。这不是正确的方法。您正在使用错误的教程。不要为此使用 AsyncTasks。重新开始,使用这个:

http://developer.android.com/reference/android/webkit/WebView.html

或者

http://www.mkyong.com/android/android-webview-example/

如果您想加载不同的页面,只需使用不同的 url 再次调用 webview.loadUrl(url)。就这么简单。

于 2013-08-26T20:12:03.167 回答