阻止AsyncTask多次运行

时间:2016-07-01 18:40:37

标签: android android-asynctask

我有一个特殊的asynctask,当它被称为它运行多次,像很多,几乎每一秒。我怎么能阻止这个?代码在下面,也许我在某个地方犯了一个我无法看到或做某事的错误。当AsyncTask成功时,我就会启动一个AlarmService。

 private void connectWithHttpGet(String Id, String encryptedTo,String encryptedId, String encryptedCu,
                                String encryptedA, String encryptedNa) {

    class HttpGetAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            URL url;
            HttpURLConnection urlConnection = null;
            String paramMerchantId = params[0];
            String paramEncryptedToken = params[1];
            String paramEncryptedCustId = params[2];
            String paramEncryptedCurrency = params[3];
            String paramEncryptedAmount = params[4];
            String paramEncryptedNarration = params[5];

            String result = null;
            String JsonResponse = null;

            BufferedReader reader = null;
            try {
                url = new URL(Config.URL);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                // is output buffer writter
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");

                JSONObject jsonParam = new JSONObject();
                jsonParam.put("id", paramMerchantId);
                jsonParam.put("at", paramEncryptedA);
                jsonParam.put("cu", paramEncryptedC);
                jsonParam.put("c", paramEncryptedT);
                jsonParam.put("n", paramEncryptedN);
                jsonParam.put("c", paramEncryptedId);

                Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
                writer.write(jsonParam.toString());
                System.out.println("input" + jsonParam.toString());
                writer.close();
                InputStream inputStream = urlConnection.getInputStream();
                System.out.println("input" + inputStream );
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String inputLine;
                while ((inputLine = reader.readLine()) != null)
                    buffer.append(inputLine + "\n");
                if (buffer.length() == 0) {
                    // Stream was empty. No point in parsing.
                    return null;
                }
                JsonResponse = buffer.toString();
                System.out.println("Response" + JsonResponse);

                return JsonResponse;




            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {

                    }
                }
            }
            return null;

        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            ObscuredSharedPreferences pref = ObscuredSharedPreferences.getPrefs(SubActivity.this, "MyPref", MODE_PRIVATE);
            final String u = pref.getString("U", null);
            final String e= = pref.getString("E", null);
            final String n = pref.getString("Nan", null);
            String space=" ";
            String breaking = "\n";
            final String greet = getString(R.string.hi)+space+n+breaking+breaking;
            final String first = getString(R.string.first);

            final ObscuredSharedPreferences.Editor editor = pref.edit();
            Firebase pay = new Firebase(Config.FIREBASE_URL);
            JSONObject ResponseObject = null;
            String str = null;
            String token = null;
            String message= null;
            String reference= null;
            try {
                ResponseObject = new JSONObject(result);
                str = ResponseObject.getJSONObject("data").getString("responsecode");
                token = ResponseObject.getJSONObject("data").getString("responsetoken");
                message= ResponseObject.getJSONObject("data").getString("responsemessage");
                reference= ResponseObject.getJSONObject("data").getString("transactionreference");


            } catch (JSONException e) {
                e.printStackTrace();
            }


            if ("00".equalsIgnoreCase(str)) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String currentDateAndTime = sdf.format(new Date());
                String body = greet+first+reference;
                System.out.println("String date:"+currentDateAndTime);

                Calendar c = Calendar.getInstance();
                c.add(Calendar.HOUR, 1);
                Date resultdate = new Date(c.getTimeInMillis());
                String dateInString = sdf.format(resultdate);
                System.out.println("String date:" + dateInString);

                Map<String, Object> update = new HashMap<String, Object>();
                update.put(z + "/t",Config.S);
                update.put(z + "/r",Config.E);
                update.put(z + "/f",Config.A);
                update.put(z + "/g", currentDateAndTime);
                update.put(z + "/y", dateInString);
                pay.updateChildren(update);
                editor.remove("S");
                editor.remove("R");
                editor.remove("A");
                editor.putString("S", Config.S);
                editor.putString("R", Config.R);
                editor.putString("A", Config.C);
                editor.apply();
                manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                        AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
                Mail.connectWithHttpGetEmail(email, body);
                mProgressDialog.dismiss();
                Intent intentHome = new Intent(getApplicationContext(), HomeActivity.class);
                startActivity(intentHome);
                finish();
            }else{
                mProgressDialog.dismiss();
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        }


    }

    HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
    // Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
    // We are passing the connectWithHttpGet() method arguments to that
    httpGetAsyncTask.execute(encryptedId, encryptedT, encryptedd, encryptedCurrency,
            encryptedA, encryptedN);
}

1 个答案:

答案 0 :(得分:0)

使用名为Volley的谷歌新图书馆,而不是所有

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/