停止AsyncTask重启HTTPPOST

时间:2016-07-24 15:25:18

标签: android android-asynctask

我有一个AsyncTask来执行交易,只要用户没有足够的余额就可以从开始开始流程,而不是只是告诉用户你没有足够的余额,它告诉用户并再次尝试,继续这样直到我必须删除应用才能停止

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

    ObscuredSharedPreferences serve = ObscuredSharedPreferences.getPrefs(PayService.this, "Serve", MODE_PRIVATE);
    String merchantId = serve.getString("MerchantId", null);
    String encryptedToken = serve.getString("EncryptedToken", null);
    String encryptedCustId = serve.getString("EncryptedCustId", null);
    String encryptedCurrency = serve.getString("EncryptedCurrency", null);
    String encryptedAmount = serve.getString("EncryptedAmount", null);
    String encryptedNarration = serve.getString("EncryptedNarration", null);

        @Override
        protected String doInBackground(String... params) {
            URL url;
            HttpURLConnection urlConnection = null;
            String paramMerchantId = merchantId;
            String paramEncryptedToken = encryptedToken;
            String paramEncryptedCustId = encryptedCustId;
            String paramEncryptedCurrency = encryptedCurrency;
            String paramEncryptedAmount = encryptedAmount;
            String paramEncryptedNarration = encryptedNarration;

            String result = null;
            String JsonResponse = null;

            BufferedReader reader = null;
            try {
                url = new URL(Config.PAY_URL_RENEW);
                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("merchantid", paramMerchantId);
                jsonParam.put("amount", paramEncryptedAmount);
                jsonParam.put("currency", paramEncryptedCurrency);
                jsonParam.put("chargetoken", paramEncryptedToken);
                jsonParam.put("narration", paramEncryptedNarration);
                jsonParam.put("custid", paramEncryptedCustId);


            //set headers and method
                Writer writer = new BufferedWriter(new  OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
                writer.write(jsonParam.toString());
                System.out.println("input" + jsonParam.toString());

           // json data
                writer.close();
                InputStream inputStream = urlConnection.getInputStream();
                System.out.println("input" + inputStream );
          //input stream
                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);
              //response data

                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(PayService.this, "MyPref", MODE_PRIVATE);
            final String userName = pref.getString("Username", null);
            final String email = pref.getString("Email", null);
            final String name = pref.getString("Name", null);
            String space=" ";
            String breaking = "\n";
            final String greet = getString(R.string.hi)+space+name+breaking+breaking;
            final String first = getString(R.string.first);
            final String insufficient = getString(R.string.insufficient);
            final String noReason = getString(R.string.no_reason);

            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;
                Calendar c = Calendar.getInstance();
                c.add(Calendar.MINUTE, 10);
                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(userName + "/subscription",Config.SUB_YES);
                update.put(userName + "/renewSub", Config.RENEW_YES);
                update.put(userName + "/activeCard",Config.CARD_ACTIVE);
                update.put(userName + "/lastSubscription", currentDateAndTime);
                update.put(userName + "/endSubscription", dateInString);
                update.put(userName + "/serviceRun",currentDateAndTime);
                pay.updateChildren(update);
                editor.remove("Subscription");
                editor.remove("Renew");
                editor.remove("ActiveCard");
                editor.putString("Subscription", Config.SUB_YES);
                editor.putString("Renew", Config.RENEW_YES);
                editor.putString("ActiveCard", Config.CARD_ACTIVE);
                editor.apply();

                AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                manager.cancel(pendingIntent);
                manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                        AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
                        ObscuredSharedPreferences serve = ObscuredSharedPreferences.getPrefs(PayService.this, "Serve", MODE_PRIVATE);
                        ObscuredSharedPreferences.Editor serveEdit = serve.edit();
                        serveEdit.clear();
                        serveEdit.apply();

                Mail.connectWithHttpGetEmail(email, body);

            }else if("5".equalsIgnoreCase(str)){
                String body = greet+insufficient;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String currentDateAndTime = sdf.format(new Date());
                Map<String, Object> update = new HashMap<String, Object>();
                update.put(userName + "/subscription", Config.SUB_NO);
                update.put(userName + "/serviceRun",currentDateAndTime);
                pay.updateChildren(update);
                editor.remove("Subscription");
                editor.putString("Subscription", Config.SUB_NO);
                editor.apply();
                Mail.connectWithHttpGetEmail(email, body);
                AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                manager.cancel(pendingIntent);
                manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                        AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
                        ObscuredSharedPreferences serve = ObscuredSharedPreferences.getPrefs(PayService.this, "Serve", MODE_PRIVATE);
                        ObscuredSharedPreferences.Editor serveEdit = serve.edit();
                        serveEdit.clear();
                        serveEdit.apply();
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }else{
                String body = greet+noReason;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String currentDateAndTime = sdf.format(new Date());
                Map<String, Object> update = new HashMap<String, Object>();
                update.put(userName + "/subscription", Config.SUB_NO);
                update.put(userName + "/serviceRun",currentDateAndTime);
                pay.updateChildren(update);
                editor.remove("Subscription");
                editor.putString("Subscription", Config.SUB_NO);
                editor.apply();
                Mail.connectWithHttpGetEmail(email, body);
                AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                manager.cancel(pendingIntent);

                manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                        AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
                        ObscuredSharedPreferences serve = ObscuredSharedPreferences.getPrefs(PayService.this, "Serve", MODE_PRIVATE);
                        ObscuredSharedPreferences.Editor serveEdit = serve.edit();
                        serveEdit.clear();
                        serveEdit.apply();
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

            }
        }


    }

0 个答案:

没有答案
相关问题