Android一組WebView的隨機,順序,倒序載入

來源:互聯網
上載者:User

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.