0

我有一个应用程序在手机上的 wifi 超出范围时崩溃。它主要从在线 txt 获取字符串,完成后我确实断开了 HTTPURLConnection,所以我没想到会崩溃。以下是相关代码;

检查网络可用性(首先检查所有使用互联网连接的代码):

public boolean isNetworkAvailable() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            //if (netInfo != null && netInfo.isConnected()) {
            return true;
        }
        return false;
    }

我在 onResume 上运行的 checkForPromptPassword 异步任务:

private class CheckForPromptPasswordAgain extends AsyncTask<Void, Void, Boolean>
    {
        //    ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            //  pdLoading.setMessage("\tFetching Database...");
            //     pdLoading.show();
        }
        @Override
        protected Boolean doInBackground(Void... params) {

            //this method will be running on background thread so don't update UI frome here
            //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
            //view GONE by default of update button



                    if (isNetworkAvailable()){
                        if (PromptForPasswordAgain()){
                            //TODO: //show update button or dialog
                            return true;
                        }else{
                            //TODO: //proceed as normal 
                            return false;
                        }
                    }


                    return false;

        }





        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);


            //this method will be running on UI thread


            if (result==true){
                promptForPassword();
            }else{

                //  showDialog("string", "string",0);
            }



            //  pdLoading.dismiss();
        }
    }

我在 OnResume() 上运行的 checkForUpdate AsyncTask:

Private class CheckForUpdate extends AsyncTask<Void, Void, Boolean>
        {
            //    ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            //  pdLoading.setMessage("\t string.");
            //     pdLoading.show();
        }
        @Override
        protected Boolean doInBackground(Void... params) {

            //this method will be running on background thread so don't update UI frome here
            //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
            //view GONE by default of update button


            if (fileExistance("data.txt")){
                try {
                    if (isNetworkAvailable()){
                        if (isDatabaseContentDifferent()){
                            //TODO: //show update button or dialog
                            return true;
                        }else{
                            //TODO: //proceed as normal 
                            return false;
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block

                    e.printStackTrace();
                }
            }else{
                Log.i("error","file data.txt does not exist in internal");
                return false;
            }

            return false;
        }


        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);


            //this method will be running on UI thread

            Button updateButton = (Button) findViewById(R.id.UpdateDatabase);
            updateButton.setVisibility(View.GONE);
            if (result==true){
                showDialog("Database Updated On Server", "The  Database App has detected a change in the database, press \"Update Database\" to account for the change(s).  ",0);
                updateButton.setVisibility(View.VISIBLE);
            }else{
                updateButton.setVisibility(View.GONE);
                //  showDialog("No Update Detected", "The Database App has detected a change in the database, press \"Update Database\" to account for the change(s).  ",0);
            }



            //  pdLoading.dismiss();
        }
    }

我正在使用的 HTTPURLClient 示例,有很多功能,但这是基本结构:

public boolean isDatabaseContentDifferent() throws IOException{
        String page = null;
        try{
            URL url = new URL(_data);
            HttpURLConnection.setFollowRedirects(true);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(false);
            con.setReadTimeout(20000);
            con.setRequestProperty("Connection", "keep-alive");
            //get etag for update check
            //String etag= "";

            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
            ((HttpURLConnection) con).setRequestMethod("GET");
            //System.out.println(con.getContentLength()) ;
            con.setConnectTimeout(5000);
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            //make seperate function for etag it doesn't work with GET
            //String etag = con.getHeaderField("etag");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println(responseCode);
            }
            StringBuffer buffer = new StringBuffer();
            int chars_read;
            //int total = 0;
            while ((chars_read = in.read()) != -1) 
            {
                char g = (char) chars_read;
                buffer.append(g);
            }
            page = buffer.toString();
            //create password.txt to internal
//TODO: checkkk
            con.disconnect();
        }catch(Exception e){
            showDialog("Database Fetch Failure","Unable to Fetch Password Database, check your internet" +
                    " connection and try again later.",0);
            Log.i("Page", "Error in isDatabaseContentDifferent()");
            return false;
        }

        if (fileExistance("data.txt")){
            if (isTextInFileDifferent(page,"data.txt")){

                return true;

            }else{
                return false;
            }

    }else{
        Log.i("Page","file data.txt does not exist IN isDatabaseContentDifferent()");
        return false;
        }
    }

任何帮助将不胜感激。谢谢。

4

0 回答 0