Android一组WebView的随机,顺序,倒序加载

写了个应用,实现了一组WebView的顺序,倒序,和随机加载。之中使用了延时,为什么要使用呢?请看下图:

技术分享


package com.zms.csdngo;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Random;


public class Main extends ActionBarActivity {
    private String urlIndex = "http://blog.csdn.net/zhoumushui/article/details/";
    private WebView mWebView;
    private String webPath;
    private int count = 0;          // 当前加载的页面ID
    private int reverseCount = 0;
    private int realCount = 0;      // 已加载的页面数
    private int limitCount = 0;   // 最大加载页面,到达此数值退出应用;为0表示不限制
    private Boolean isLimit = false;
    private TextView tvState = null;
    private TextView mTimeHint = null;
    private TextView mTimeCount = null;
    private TextView tvWebHour = null;

    private TextView tvLimit = null;
    private EditText etLimit = null;

    private int loadMode = 3;   // 1-顺序加载;2-倒序加载;3-随机加载

    private Button btnShowHide;
    private Button btnChangeMode;
    private static PowerManager.WakeLock wakeLock;
    private int timeSec = 0;    // 秒数,计时用
    private int webHour = 8;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.mWebView);
        tvState = (TextView) findViewById(R.id.tvState);
        mTimeHint = (TextView) findViewById(R.id.mTimeHint);
        mTimeCount = (TextView) findViewById(R.id.mTimeCount);
        tvWebHour = (TextView) findViewById(R.id.tvWebHour);
        tvLimit = (TextView) findViewById(R.id.tvLimit);
        etLimit = (EditText) findViewById(R.id.etLimit);
        btnShowHide = (Button) findViewById(R.id.btnShowHide);
        btnChangeMode = (Button) findViewById(R.id.btnChangeMode);

        initModeBtn();
        initUrl();
        count = 0;
        reverseCount = urlArray.length - 1;
        setLimit(tvState);
        //setMode(mTextView);
        new Thread(new TimeThread()).start();   // 计时线程
        new Thread(new loadThread()).start();  // 加载线程
    }

    final Handler timeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    timeSec++;
                    String strTime = "";
                    if (timeSec < 60) {  // 1分钟以下情况
                        strTime = timeSec + "秒";
                    } else if (timeSec < 3600) {  // 1小时以下情况
                        int minutes = timeSec / 60;
                        int second = timeSec % 60;
                        strTime = minutes + "分" + second + "秒";
                    } else {
                        int hours = timeSec / 3600;
                        int minutes = (timeSec - hours * 3600) / 60;
                        int second = timeSec % 60;
                        strTime = hours + "时" + minutes + "分" + second + "秒";
                    }
                    mTimeCount.setText("运行时长:" + strTime);
                    tvWebHour.setText("设备时间" + getTime(1) + "时"+getTime(2)+"分"+getTime(3)+"秒");
            }
            super.handleMessage(msg);
        }
    };

    public class TimeThread implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    Message message = new Message();
                    message.what = 1;
                    timeHandler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void connectWifi() {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    final Handler loadHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    if (loadMode == 1) {    // 顺序加载
                        if (count < urlArray.length) {
                            webPath = urlIndex + urlArray[count++];
                        } else {
                            count = 0;
                            webPath = urlIndex + urlArray[count++];
                        }
                    } else if (loadMode == 2) { // 倒序加载
                        if (count >= urlArray.length) {
                            count = 0;
                        }
                        reverseCount = urlArray.length - 1 - (count++);
                        webPath = urlIndex + urlArray[reverseCount];
                    } else { // 默认:随机加载
                        count = new Random().nextInt(urlArray.length);     // 0到(urlArray.length-1)
                        if (getTime(3) % 5 == 0) {// 如果当前秒数对5求余为0,则加载最近5篇
                            count = (urlArray.length - 5) + new Random().nextInt(5); // 0到4,加上
                        }
                        webPath = urlIndex + urlArray[count];
                    }
                    keepScreenOn(Main.this, true);
                    loadBlog(webPath);
                    break;
                case 2:
                    tvState.setText("Network Error");
                    keepScreenOn(Main.this, false);
                    /*
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    connectWifi();
                    */
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public class loadThread implements Runnable {

        @Override
        public void run() {
            while (true) {
                if (isNetworkConnected(Main.this)) {
                    try {
                        webHour = getTime(1);

                        if (webHour < 0 || webHour > 24) {
                            webHour = 8;
                        }
                        if (webHour >= 23 || webHour < 7) { // [0,7) AND [23,0)
                            int randomId = 1 + new Random().nextInt(3);     // 1-3
                            mTimeHint.setText("延时" + randomId + "分");
                            Thread.sleep(randomId * 60000);
                        } else if ((webHour >= 8 && webHour <= 12) || (webHour >= 14 && webHour <= 18)) {
                            int randomId = 1 + new Random().nextInt(3);     // 1-3
                            mTimeHint.setText("延时" + randomId + "秒");
                            Thread.sleep(randomId * 1000);
                        } else {
                            int randomId = 1 + new Random().nextInt(3);     // 1-3
                            mTimeHint.setText("延时" + (2 * randomId) + "秒");
                            Thread.sleep(randomId * 2000);
                        }
                        Message message = new Message();
                        message.what = 1;
                        loadHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Message message = new Message();
                    message.what = 2;
                    loadHandler.sendMessage(message);

                }
            }
        }
    }

    public int getTime(int type) {
        Date date = new Date();
        if (type == 1) {
            return date.getHours();
        } else if (type == 2) {
            return date.getMinutes();
        } else if (type == 3) {
            return date.getSeconds();
        } else {
            return 0;
        }
    }

    private void loadBlog(String path) {
        mWebView.loadUrl(path);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // return super.shouldOverrideUrlLoading(view, url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // 截取URL的八位ID
                String subString = url.toString().substring(
                        url.toString().length() - 8, url.toString().length());
                super.onPageFinished(view, url);

                if (!subString.equals(urlArray[urlArray.length - 1])) { // 是否是数组最后一个元素
                    realCount++;
                    if (loadMode == 2) {
                        tvState.setText("页面" + (reverseCount + 1) + "/" + urlArray.length + "--" + subString
                                + "加载完毕,成功加载了" + realCount + "个页面");
                    } else {
                        tvState.setText("页面" + count + "/" + urlArray.length + "--" + subString
                                + "加载完毕,成功加载了" + realCount + "个页面");
                    }
                    if (isLimit && (realCount >= limitCount)) {
                        ExitApp(tvState);
                    }
                } else {
                    realCount++;
                    if (loadMode == 2) {
                        tvState.setText("页面" + (reverseCount + 1) + "/" + urlArray.length + "--" + subString
                                + "加载完毕,成功加载了" + realCount + "个页面");
                    } else {
                        tvState.setText("页面" + count + "/" + urlArray.length + "--" + subString
                                + "加载完毕,共加载了" + realCount + "个页面");
                    }
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.e("CSDN", "" + errorCode + description);
                tvState.setText("加载失败,请稍候再试.");
            }
        });
    }


    public void initModeBtn() {
        // initial Mode Button Text
        if (loadMode == 1) {
            btnChangeMode.setText("顺序模式");
        } else if (loadMode == 2) {
            btnChangeMode.setText("倒序模式");
        } else if (loadMode == 3) {
            btnChangeMode.setText("随机模式");
        }
    }

    public void ExitApp(View view) {
        keepScreenOn(Main.this, false);
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public void showHide(View view) {
        if (mWebView.getVisibility() == View.GONE) {
            mWebView.setVisibility(View.VISIBLE);
            btnShowHide.setText("隐藏");
        } else if (mWebView.getVisibility() == View.VISIBLE) {
            mWebView.setVisibility(View.GONE);
            btnShowHide.setText("显示");
        }
    }

    public void setLimit(View view) {
        if (etLimit.getText().toString() != null && etLimit.getText().toString().trim().length() > 0) {
            limitCount = Integer.parseInt(etLimit.getText().toString());
        }
        if (limitCount < 0) {
            limitCount = 0;
        }
        if (limitCount == 0) {
            isLimit = false;
            tvLimit.setText("限制规则:不限制");
        } else if (limitCount > 0) {
            isLimit = true;
            tvLimit.setText("限制规则:加载" + limitCount + "个页面后退出");
        }
    }

    public void changeMode(View view) {
        if (loadMode == 1) {
            loadMode = 2;
            btnChangeMode.setText("倒序模式");
        } else if (loadMode == 2) {
            loadMode = 3;
            btnChangeMode.setText("随机模式");
        } else if (loadMode == 3) {
            loadMode = 1;
            btnChangeMode.setText("顺序模式");
        }
    }

    // 网络状态
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static void keepScreenOn(Context context, boolean on) {
        if (on) {
            if (wakeLock == null) {
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "==KeepScreenOn==");
                wakeLock.acquire();
            } else {
                Log.e("ZMS", "WakeLock Already On");
            }
        } else {
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
        }
    }

    public String[] urlArray = new String[82]; // ##### Modify Me #####

    // ##### Modify Me #####
    public void initUrl() {
        urlArray[81] = "42245481"; // 2014-12-29 21:22
        urlArray[80] = "42192861"; // 2014-12-27 14:40
        urlArray[79] = "42149731"; // 2014-12-25 17:49
        urlArray[78] = "42127681"; // 2014-12-24 19:59
        urlArray[77] = "42110329"; // 2014-12-23 21:51
        urlArray[76] = "42085939"; // 2014-12-22 21:14
        urlArray[75] = "42042547"; // 2014-12-20 14:25
        urlArray[74] = "42023747"; // 2014-12-19 09:11
        urlArray[73] = "42001049"; // 2014-12-18 09:02
        urlArray[72] = "41982749"; // 2014-12-17 17:42
        urlArray[71] = "41964147"; // 2014-12-16 18:45
        urlArray[70] = "41909621"; // 2014-12-13 14:03
        urlArray[69] = "41898205"; // 2014-12-12 19:55
        urlArray[68] = "41852845"; // 2014-12-11 15:56
        urlArray[67] = "41807913"; // 2014-12-08 19:55
        urlArray[66] = "41787113"; // 2014-12-07 13:58
        urlArray[65] = "41773471";
        urlArray[64] = "41751259";
        urlArray[63] = "41674841";
        urlArray[62] = "41651909";
        urlArray[61] = "41623903";
        urlArray[60] = "41593769";
        urlArray[59] = "41577725";
        urlArray[58] = "41559167";
        urlArray[57] = "41515985";
        urlArray[56] = "41493939";
        urlArray[55] = "41452531";
        urlArray[54] = "41444931";
        urlArray[53] = "41378661";
        urlArray[52] = "41310305";
        urlArray[51] = "41276657";
        urlArray[50] = "41039497";
        urlArray[49] = "41006711";
        urlArray[48] = "41006711";
        urlArray[47] = "40897455";
        urlArray[46] = "40865095";
        urlArray[45] = "40817269";
        urlArray[44] = "40779347";
        urlArray[43] = "40737065";
        urlArray[42] = "40677441";
        urlArray[41] = "40648971";
        urlArray[40] = "40614011";
        urlArray[39] = "40580995";
        urlArray[38] = "40544365";
        urlArray[37] = "40507193";
        urlArray[36] = "40423803";
        urlArray[35] = "40227437";
        urlArray[34] = "40160843";
        urlArray[33] = "40082987";
        urlArray[32] = "40051331";
        urlArray[31] = "40021129";
        urlArray[30] = "39997481";
        urlArray[29] = "39973739";
        urlArray[28] = "39936867";
        urlArray[27] = "39897617";
        urlArray[26] = "39862237";
        urlArray[25] = "39834141";
        urlArray[24] = "39777229";
        urlArray[23] = "39759943";
        urlArray[22] = "39741221";
        urlArray[21] = "39722311";
        urlArray[20] = "39700219";
        urlArray[19] = "39674051";
        urlArray[18] = "39645901";
        urlArray[17] = "39618057";
        urlArray[16] = "39585513";
        urlArray[15] = "39558107";
        urlArray[14] = "39527977";
        urlArray[13] = "39502685";
        urlArray[12] = "39480497";
        urlArray[11] = "39454145";
        urlArray[10] = "39454145";
        urlArray[9] = "39434451";
        urlArray[8] = "39401061";
        urlArray[7] = "39377419";
        urlArray[6] = "39346957";
        urlArray[5] = "39323633";
        urlArray[4] = "39296439";
        urlArray[3] = "39274019";
        urlArray[2] = "39257041";
        urlArray[1] = "39234287";
        urlArray[0] = "39210795";
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            // ToDo:Setting Menu
            Toast.makeText(Main.this, "ToDo", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_exit) {
            ExitApp(tvState);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        keepScreenOn(Main.this, false);
    }

    @Override
    protected void onResume() {
        // ToDo:Keep Screen Always On When Running
        super.onResume();
    }
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。