热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

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

写了个应用,实现了一组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) {
                            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();
    }
}



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


推荐阅读
  • 如果应用程序经常播放密集、急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了。因为MediaPlayer存在如下缺点:1)延时时间较长,且资源占用率高 ... [详细]
  • 本文介绍了如何在 ASP.NET 中设置 Excel 单元格格式为文本,获取多个单元格区域并作为表头,以及进行单元格合并、赋值、格式设置等操作。 ... [详细]
  • Framework7:构建跨平台移动应用的高效框架
    Framework7 是一个开源免费的框架,适用于开发混合移动应用(原生与HTML混合)或iOS&Android风格的Web应用。此外,它还可以作为原型开发工具,帮助开发者快速创建应用原型。 ... [详细]
  • 解决Bootstrap DataTable Ajax请求重复问题
    在最近的一个项目中,我们使用了JQuery DataTable进行数据展示,虽然使用起来非常方便,但在测试过程中发现了一个问题:当查询条件改变时,有时查询结果的数据不正确。通过FireBug调试发现,点击搜索按钮时,会发送两次Ajax请求,一次是原条件的请求,一次是新条件的请求。 ... [详细]
  • 第二十五天接口、多态
    1.java是面向对象的语言。设计模式:接口接口类是从java里衍生出来的,不是python原生支持的主要用于继承里多继承抽象类是python原生支持的主要用于继承里的单继承但是接 ... [详细]
  • LDAP服务器配置与管理
    本文介绍如何通过安装和配置SSSD服务来统一管理用户账户信息,并实现其他系统的登录调用。通过图形化交互界面配置LDAP服务器,确保用户账户信息的集中管理和安全访问。 ... [详细]
  • 本文详细介绍了Java代码分层的基本概念和常见分层模式,特别是MVC模式。同时探讨了不同项目需求下的分层策略,帮助读者更好地理解和应用Java分层思想。 ... [详细]
  • Spring – Bean Life Cycle
    Spring – Bean Life Cycle ... [详细]
  • [c++基础]STL
    cppfig15_10.cppincludeincludeusingnamespacestd;templatevoidprintVector(constvector&integer ... [详细]
  • DAO(Data Access Object)模式是一种用于抽象和封装所有对数据库或其他持久化机制访问的方法,它通过提供一个统一的接口来隐藏底层数据访问的复杂性。 ... [详细]
  • 本文介绍了在 Java 编程中遇到的一个常见错误:对象无法转换为 long 类型,并提供了详细的解决方案。 ... [详细]
  • Python 数据可视化实战指南
    本文详细介绍如何使用 Python 进行数据可视化,涵盖从环境搭建到具体实例的全过程。 ... [详细]
  • 实验九:使用SharedPreferences存储简单数据
    本实验旨在帮助学生理解和掌握使用SharedPreferences存储和读取简单数据的方法,包括程序参数和用户选项。 ... [详细]
  • 两个条件,组合控制#if($query_string~*modviewthread&t(&extra(.*)))?$)#{#set$itid$1;#rewrite^ ... [详细]
  • 解决Parallels Desktop错误15265的方法
    本文详细介绍了在使用Parallels Desktop时遇到错误15265的多种解决方案,包括检查网络连接、关闭代理服务器和修改主机文件等步骤。 ... [详细]
author-avatar
拉扯作乱_991
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有