如何逐个连续加载URL

时间:2011-03-14 10:46:25

标签: android url webview

我想逐个加载URL。我使用String数组来存储URL。我的要求是,如果webview加载了第一个url,它应该在页面启动时以及当页面将其打开时打印msg“page started”应显示“页面已完成”。第一个url加载完成后,它应该加载第二个URL并继续相同的过程。

我写的编码如下:

package com.browser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class browser extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final String[] url={"http://www.yahoo.com","http://www.google.com","http://www.ibnlive.com"};
        final MyWebView mwv = new MyWebView(this); 
        mwv.setWebViewClient(new myweb()); 
        new Thread(new Runnable(){
            public void run(){
                Log.d("runThread","runthread");
                for(int i=0;i<2;i++){
                    openbrowser(url[i]);
                }

            }

            private void openbrowser(String url) {

                mwv.getSettings().setJavaScriptEnabled(true); 
                mwv.loadUrl(url);   
                Log.d("",""+url);
                setContentView(mwv);
            }
        }).start();
    }


    public class MyWebView extends WebView{

        public MyWebView(Context context) {
            super(context);

        }
    }
    public class myweb extends WebViewClient{
        @Override       
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            System.out.println("LOADING");

            return false;
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            System.out.println("PageStarted: " + url);
        }

        @Override   
        public void onPageFinished(WebView view, String url){
            System.out.println("PageFinished: " + url);
        }
    }


    }
    ///indented code <--remove this

它只加载最后一个网址。

6 个答案:

答案 0 :(得分:5)

您可以使用以下代码在webview中逐个加载网址。这段代码只是逐个加载你只看到或不能看到所有网址的网址,但你可以看到最后一个网址。

public class WebViewsScreenActivity extends Activity {

    private WebView mwebview;
    int i =0;
    private WebViewsScreenActivity _activity;
    ProgressDialog _dilog;
    private String[] Urls = {"http://www.google.com","http://www.gmail.com","http://www.yahoo.com"}; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
         getWindow().requestFeature(Window.FEATURE_PROGRESS);  
        mwebview = new WebView(this);
        setContentView(mwebview);
        _activity = this;  
        mwebview.getSettings().setJavaScriptEnabled(true);
        mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        if(checkInternetConnection(_activity)){
            if(savedInstanceState==null)    
                mwebview.loadUrl(Urls[i]);
            else
                mwebview.restoreState(savedInstanceState);
        }
        else{
            //showAlert  "Unable to Connect Server"
        }
         mwebview.setWebChromeClient(new WebChromeClient() {

                @Override
       public void onProgressChanged(WebView view, int progress) {
                 if(mwebview.getVisibility()==View.VISIBLE)
                 {
                 WebViewsScreenActivity.this.setProgress(progress * 100);

                 }
                }
              });
        mwebview.setWebViewClient(new HelloWebViewClient());
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            mwebview.goBack();
            return true;
        }
        else
            return super.onKeyUp(keyCode, event);
    }


    //To check whether network connection is available on device or not
    private boolean checkInternetConnection(Activity _activity) {
        ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected())
            return true;
        else
            return false;
    }//checkInternetConnection()



    //HelloWebViewClient class for webview
    private class HelloWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
                    Toast.makeText(getApplicationContext(), "Loading started...!"+Urls[i], Toast.LENGTH_SHORT).show();

        }
        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);

        }
        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
                    Toast.makeText(getApplicationContext(), "Loading done...!"+Urls[i], Toast.LENGTH_SHORT).show();
            i++;
            if(i<Urls.length)
                view.loadUrl(Urls[i]);
        }
    } //HelloWebViewClient-class
}//AccountsScreenActivity-class

在manifestast文件中添加权限,如下所示::

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vl.agarwal"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".WebViewsScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

答案 1 :(得分:5)

试试这个...

int position=0;

textview.setText("page started");
browser.loadUrl("your first url");
browser.setWebChromeClient(new WebChromeClient()
{
    public void onProgressChanged(WebView view, int progress) 
    {
       if(progress == 100)
       {
          textview.setText("page finished");
          if(position==0)
          {
            browser.loadUrl("your second url");
            position=1;
            textview.setText("page started");
          } 
          if(position==1)
          {
            browser.loadUrl("your third url");
            position=2;
            textview.setText("page started");
          } 
       }
    }
});

您还可以显示Toast而不是TextView ..

答案 2 :(得分:3)

我试图模拟并想出以下内容:

package com.mywebslider;


import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

public class WebSliderActivity extends Activity {

    TextView number;
    WebView mWebView;
    CountDownTimer mTimer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        number = (TextView) findViewById(R.id.number);
        mTimer=new CountDownTimer(15000, 1000) {

         String[] myArray={"http://www.upc.nl/","http://www.google.com","http://www.quickspot.nl"}; 


            int currentIndex=0; 
            public void onTick(long millisUntilFinished) {

                number.setText("seconds remaining: " + millisUntilFinished / 1000);
            }
             //code comment start
             // i think this part could be written better
             // but it works!!!
            public void onFinish() {
                if (currentIndex<myArray.length) {
                    number.setText("done!");
                    mWebView.loadUrl(myArray[currentIndex]);
                    currentIndex++;
                } else {
                    currentIndex=0;
                    if (currentIndex<myArray.length)
                    number.setText("done!");
                    mWebView.loadUrl(myArray[currentIndex]);
                    currentIndex++;
                    mTimer.start();
                }

                    mTimer.start();

            }
            //code comment end
         };

        mTimer.start();
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://stackoverflow.com");
        mWebView.setWebViewClient(new WebSliderWebViewClient(){
        @Override  
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(mWebView, url);
            Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();

        }  

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
           Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();

        }
    });


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class WebSliderWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

除了这个工作的事实,数组循环可以做得更好。 main.xml应为:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView 
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="0dp" 
    android:layout_weight="1"
    />

<TextView  
   android:id="@+id/number" 
   android:layout_width="fill_parent"
   android:layout_height="0dp" 
   android:layout_weight="1"
    />

</LinearLayout>

输出将为50/50屏幕。 一个用于WebView,另一个用于TextView中的计数器。

答案 3 :(得分:2)

问题是你不要等待onPageStarted()和onPageFinished返回任何东西。相反,你的代码只是一个接一个地快速加载网址,你只看到最后一个。

您需要修改for()循环以等待onPagefinished()方法在加载另一个页面之前返回。

答案 4 :(得分:2)

尝试编写出WebViewClient扩展名,以便在加载完成时通知您的Activity。我试图修改你的代码来做到这一点:

package com.browser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Browser extends Activity {

private MyWebView mwv = null;
private MyWeb myweb = null;
private List<String> urls = null;
private String[] url = new String[] {"http://www.yahoo.com","http://www.google.com","http://www.ibnlive.com"};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mwv = new MyWebView(this);
    myweb = new MyWeb(this);
    mwv.setWebViewClient(myweb); 
    urls = Arrays.asList(url);
    loadNextUrl(null);
}

private loadNextUrl(String fromUrl) {
    if (fromUrl == null) {
        myweb.setOriginalUrl(urls.get(0));
        mwv.loadUrl(urls.get(0));
    } else {
        if (urls.indexOf(fromUrl) == urls.size() - 1) return;
        String newUrl = urls.get(urls.indexOf(fromUrl) + 1);
        myweb.setOriginalUrl(newUrl);
        mwv.loadUrl(newUrl);
    }
}


public class MyWebView extends WebView{

    public MyWebView(Context context) {
        super(context);

    }
}
public class MyWeb extends WebViewClient{
    Browser activity = null;

    // Prevent redirects from messing with URL array
    String originalUrl = null;

    public MyWeb(Browser activity) {
        this.activity = activity;
    }

    public setOriginalUrl(String url) {
        this.originalUrl = url;
    }

    @Override       
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
        System.out.println("LOADING");

        return false;
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {

        System.out.println("PageStarted: " + url);
    }

    @Override   
    public void onPageFinished(WebView view, String url){
        System.out.println("PageFinished: " + url);
        activity.loadNextUrl(originalUrl);
    }
}


}

答案 5 :(得分:1)

您可以使用队列来保存要一个接一个地加载的网址。

Queue<String> mQueue = new LinkedList<String>();
...

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    mQueue.add("http://url1");
    mQueue.add("http://url2");
    mQueue.add("http://urln");
    ...
    String url = mQueue.remove();
    mwv.loadurl(url);
}
...
public class myweb extends WebViewClient{
    @Override       
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
        System.out.println("LOADING");

        return false;
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        System.out.println("PageStarted: " + url);
    }

    @Override   
    public void onPageFinished(WebView view, String url){
        System.out.println("PageFinished: " + url);
        String url = null;
        url = mQueue.remove();
        if (url != null) {
            view.loadUrl(url);
        }
    }
}