如何优化通过php/android从mysql获取数据?

jhkqcmku  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(295)

介绍
我有一个应用程序,想强迫用户更新它,如果一个新版本是在谷歌播放市场。这在下面的代码中可以正常工作,但不是很稳定。我是通过asynctask和从php文件获取数据来完成的。但它给了我一种感觉,那就是一定有更好的方法或者一种让它更稳定的方法。
问题
如何设置过程的超时,例如由于用户的Internet连接非常低?
代码
获取\最新\ apk.php

<?PHP

    /*  GET APK VERSION FROM ANDROID DEVICE
        Example: [PATH]/get_newest_apk.php?apkversion=6
    */
    if($_GET["apkversion"]){
        $apkversion= $_GET["apkversion"];

        //MYSQL LOGIN PARAMETERS
        $host = '*****';
        $user = '*****';
        $pass = '*****';
        $db =   '*****';

        $mysqli = new mysqli($host, $user, $pass, $db);

            $result = $mysqli->query("SELECT MAX(VERSION) FROM TBL_APK");
            $row = $result->fetch_row();
            $count = $row[0];

            if($count > $apkversion){
                //Newer APK is avaiable
                echo "1";
            }else{
                //There is no never APK avaiable
                echo "2";
            }

    }else{
        //Error by GETTING apkversion from Android device
        echo "3";
    }
?>

异步任务类

class checkForNewAPK extends AsyncTask<Void, Void, String> {
    @Override
    protected void onPreExecute() {
        //Do not show the user a progress because he don't want to see it in every onResume
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        int intResult = Integer.parseInt(s);

        //strResult as intResult; 1 = Newer APK avaiable, 2 = No newer APK avaiable, 3 = Error at $_GET["apkversion"] line 6
        if(intResult == 1){
            //Force to Update App
            Log.v("APKResult: ", "1");
        }else if(intResult == 2){
            //No update needed
            Log.v("APKResult: ", "2");
        }else if(intResult == 3){
            //Error in PHP-File
            Log.v("APKResult: ", "3");
        }else{
            //Unknown error
            Log.v("APKResult: ", "Unkown Error");
        }
    }

    //in this method we are fetching the json string
    @Override
    protected String doInBackground(Void... voids) {
        try {
            int intApkVersion = getApplication().getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            URL url = new URL(strUrlGetNewestAPK+"?apkversion="+intApkVersion);
            String strResultFromEcho;

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            StringBuilder strResult = new StringBuilder();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            while ((strResultFromEcho = bufferedReader.readLine()) != null) {
                strResult.append(strResultFromEcho + "\n");
            }

            return strResult.toString().trim();
        } catch (Exception e) {
            return null;
        }
    }
}
ltskdhd1

ltskdhd11#

如何设置过程的超时,例如由于用户的Internet连接非常低?
你需要使用 setConnectTimeout 以及
setReadTimeout setConnectTimeout 设置打开指向此urlconnection引用的资源的通信链接时要使用的指定超时值(以毫秒为单位)。如果超时在建立连接之前过期,则会引发java.net.sockettimeoutexception。超时为零被解释为无限超时。 setReadTimeout 将读取超时设置为指定的超时(毫秒)。非零值指定在建立到资源的连接时从输入流读取时的超时。如果在有数据可读取之前超时,则 java.net.SocketTimeoutException 升起。超时为零被解释为无限超时。
样本代码

HttpURLConnection con = (HttpURLConnection) url.openConnection();
   con.setConnectTimeout(3000); //set connection time out in milliseconds
   con.setReadTimeout(3000); // set read time out in milliseconds

在代码中进行以下更改

class checkForNewAPK extends AsyncTask<Void, Void, String> {
    @Override
    protected void onPreExecute() {
        //Do not show the user a progress because he don't want to see it in every onResume
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        int intResult = Integer.parseInt(s);

        //strResult as intResult; 1 = Newer APK avaiable, 2 = No newer APK avaiable, 3 = Error at $_GET["apkversion"] line 6
        if(intResult == 1){
            //Force to Update App
            Log.v("APKResult: ", "1");
        }else if(intResult == 2){
            //No update needed
            Log.v("APKResult: ", "2");
        }else if(intResult == 3){
            //Error in PHP-File
            Log.v("APKResult: ", "3");
        }else{
            //Unknown error
            Log.v("APKResult: ", "Unkown Error");
        }
    }

    //in this method we are fetching the json string
    @Override
    protected String doInBackground(Void... voids) {
        try {
            int intApkVersion = getApplication().getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            URL url = new URL(strUrlGetNewestAPK+"?apkversion="+intApkVersion);
            String strResultFromEcho;

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(3000); //set connection time outt in milliseconds
            con.setReadTimeout(3000); // set read time outt in milliseconds

            StringBuilder strResult = new StringBuilder();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            while ((strResultFromEcho = bufferedReader.readLine()) != null) {
                strResult.append(strResultFromEcho + "\n");
            }

            return strResult.toString().trim();
        } catch (SocketTimeoutException e) {
            // this block code execute when time out exception is occur
            // you need to perform your logic here when time out exception occur
            return "Request timeout occur.\nTap on \'TRY AGAIN\' to retry";
        }
    }
}

注意:您也可以使用库进行api调用

你可以用 Volley 图书馆
volley是一个http库,它使android应用程序的联网变得更容易,最重要的是,更快。截击在github上可用。
来自文档
凌空提供以下好处:
网络请求的自动调度。
多个并发网络连接。
具有标准http缓存一致性的透明磁盘和内存响应缓存。支持请求优先级。
取消请求api。您可以取消单个请求,也可以设置要取消的请求块或请求范围。
易于定制,例如重试和退避。
强大的排序功能,使您可以轻松地使用从网络异步获取的数据正确填充ui。
调试和跟踪工具。
你可以用 Retrofit 图书馆
square,inc.针对android和java的类型安全http客户端。改装github链接
改装vs凌空
请阅读这篇关于android网络库的比较文章:okhttp、reformation和volley

相关问题