一旦otp从android中的Inbox读取,如何解雇进度条?

时间:2016-04-21 06:12:41

标签: android

我有一个Otp验证屏幕,其中我有一个带有计时器的进度条,我想要的是一旦从收件箱中读取Otp,如果从收件箱中成功读取,则关闭此进度条然后关闭进度条并执行Jsons Url如果没有则显示进度条计时器直到没有从Inbox读取短信。为此我使用广播接收器。请帮助我。

这是我的MainActivity代码: -

 public class COtpAutoVerificationScreen extends Fragment {
    private static String s_szResult = "";
    private final String m_szOTPVERIFICATIONURL = "http://202.131.144.132:8080/resting/rest/json/metallica/validateOTPInJSON";
    public ProgressBar pb;
    private View m_Main;
    private int m_n_ProgressStatus = 0;
    private CRegistrationSessionManagement m_oSessionManagement;
    private String m_szMobileNumber;
    private String m_szEncryptedPassword;
    private CircularProgressView m_ProgressView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        m_Main = inflater.inflate(R.layout.otp_auto_verified, container, false);
        getUserDetails();// getuser deatails....
        init();// initialize controls...
        return m_Main;

    }

    private void getUserDetails() {
        m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
    }

    private void init() {
        m_ProgressView = (CircularProgressView) m_Main.findViewById(R.id.progress_view);
        m_ProgressView.startAnimation();
        m_ProgressView.setVisibility(View.GONE);

        pb = (ProgressBar) m_Main.findViewById(R.id.pb);
        final TextView tv = (TextView) m_Main.findViewById(R.id.tv);
        @SuppressWarnings("UnusedAssignment") final TextView validationText = (TextView) m_Main.findViewById(R.id.validatingmessage);
        tv.setText("00:00");
        //Initialize a new CountDownTimer instance
        long m_MillisInFuture = 30000;
        long m_CountDownInterval = 1000;
        new CountDownTimer(m_MillisInFuture, m_CountDownInterval) {
            public void onTick(long millisUntilFinished) {
                @SuppressWarnings("UnusedAssignment") long millis = millisUntilFinished;
                String hms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
                System.out.println(hms);
                tv.setText(hms);
                //Another one second passed
                //Each second ProgressBar progress counter added one
                m_n_ProgressStatus += 1;
                pb.setProgress(m_n_ProgressStatus);
            }

            public void onFinish() {
                // retreive user data from shared preferencce........
                HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
                m_szEncryptedPassword = user.get(CRegistrationSessionManagement.s_szKEY_PASSWORD).trim();
                m_szMobileNumber = user.get(CRegistrationSessionManagement.s_szKEY_MOBILENUMBER).trim();
                // exc=ecuting request for otp verfiifcation to server
                new COtpVerify().execute();
            }
        }.start();
        // retreive progress bar count........
        int progressBarMaximumValue = (int) (m_MillisInFuture / m_CountDownInterval);
        //Set ProgressBar maximum value
        //ProgressBar range (0 to maximum value)
        pb.setMax(progressBarMaximumValue);
        //Display the CountDownTimer initial value
        tv.setText(progressBarMaximumValue + "Seconds...");
    }

    //  sending OTP to server to verify Otp
    private class COtpVerify extends AsyncTask<String, Void, String> {
        public JSONObject m_oResponseobject;
        public String m_szResponseAgentCode;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            m_ProgressView.setVisibility(View.VISIBLE);
        }

        @SuppressWarnings("deprecation")
        @Override
        protected String doInBackground(String... args) {
            InputStream inputStream;
            try {
                // 1. create HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost(m_szOTPVERIFICATIONURL);
                String json;
                // 3. build jsonObject
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("agentCode", m_szMobileNumber);
                jsonObject.put("pin", m_szEncryptedPassword);
                jsonObject.put("otpCode", COTPVerificationDataStorage.getInstance().getM_szOtp());
                // 4. convert JSONObject to JSON to String
                json = jsonObject.toString();
                // 5. set json to StringEntity
                StringEntity se = new StringEntity(json);
                // 6. set httpPost Entity
                httpPost.setEntity(se);
                // 7. Set some headers to inform server about the type of the content
                httpPost.setHeader("Content-type", "application/json");
                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPost);
                HttpEntity entity = httpResponse.getEntity();
                // 9. receive response as inputStream
                inputStream = entity.getContent();
                System.out.print("InputStream...." + inputStream.toString());
                System.out.print("Response...." + httpResponse.toString());
                StatusLine statusLine = httpResponse.getStatusLine();
                System.out.print("statusLine......" + statusLine.toString());
                ////Log.d("resp_body", resp_body.toString());
                int statusCode = statusLine.getStatusCode();
                // 10. convert inputstream to string
                if (statusCode == 200) {
                    // 10. convert inputstream to string
                    s_szResult = CJsonsResponse.convertInputStreamToString(inputStream);
                    //String resp_body =
                } else
                    s_szResult = "Did not work!";
            } catch (Exception e) {
                Log.d("InputStream", e.getLocalizedMessage());
            }
            System.out.println("resul" + s_szResult);
            // 11. return s_szResult
            return s_szResult;
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(final String result) {

            m_ProgressView.setVisibility(View.GONE);
            try {
                m_oResponseobject = new JSONObject(result);// getting response from server

                getResponse();// getting response from server ...............


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


        public void getResponse() throws JSONException {
            // if server response is successfull then......
            if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("Transaction Successful")) {
                // if server response is success then setting response odata in shared prefernce...
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CLoginScreen()).commit();
                CSnackBar.getInstance().showSnackBarSuccess(m_Main.findViewById(R.id.mainLayout), "OTP verified successfully", getActivity());
            }
            // if response from server is m_szOtp mismatch.....
            else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("OTP MisMatch")) {
                CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();

                    }
                }, 3000);
            }
            // if response from server is m_szOtp empty then......
            else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("otpCode Can Not Be Empty")) {
                CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();

                    }
                }, 3000);
            }
        }

    }

}

这是我的BroadcastReceiver类: -

    public class CSmsBroadcastReceiver extends BroadcastReceiver {
    private static final String s_szTAG = CSmsBroadcastReceiver.class.getSimpleName();
    private static String m_szOtpCode;

    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                Object[] pdusObj = (Object[]) bundle.get("pdus");
                assert pdusObj != null;
                for (Object aPdusObj : pdusObj) {
                    @SuppressWarnings("deprecation") SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String message = currentMessage.getDisplayMessageBody();

                    Log.e(s_szTAG, "Received SMS: " + message + ", Sender: " + phoneNumber);

                    // checking sms sender address....
                    if (phoneNumber.toLowerCase().contains("+919971599707".toLowerCase())) {
                        // verification code from sms
                        m_szOtpCode = getVerificationCode(message);
                        assert m_szOtpCode != null;
                        String input = m_szOtpCode.trim();

                        Log.e(s_szTAG, "OTP received: " + m_szOtpCode);
                        COTPVerificationDataStorage.getInstance().setM_szOtp(input);// getting otp from SMS and set to otpverificationstorage class
                    } else {
                        return;
                    }

                }
            }
        } catch (Exception e) {
            Log.e(s_szTAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Getting the OTP from sms message body
     * ':' is the separator of OTP from the message
     *
     * @param message
     * @return
     */
    @SuppressWarnings("JavaDoc")
    private String getVerificationCode(String message) {
        String code;
        int index = message.indexOf(":");

        if (index != -1) {
            int start = index + 2;
            int length = 6;
            code = message.substring(start, start + length);
            return code;
        }
        COTPVerificationDataStorage.getInstance().setM_szOtp(m_szOtpCode);
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

基本上,您希望在需要的消息到来时将数据从广播接收器发送到活动。您可以使用interface进行通信 在你BroadcastReceiver创建这样的界面

public interface OnSmsReceivedListener {
    public void onSmsReceived(String message);
}

添加一个方法来初始化接口引用

OnSmsReceivedListener smsListener;
public void setOnSmsReceivedListener(Context context) {
    this.smsListener = (OnSmsReceivedListener) context;
}

使用此引用来调用onReceive()方法

中的函数
 smsListener.onSmsReceived("Message Received!!!");

您已完成发布数据,现在在您的Activity中实现界面并关闭您的对话框。

public class SampleActivity extends Activity implements OnSmsReceivedListener
@Override
public void onSmsReceived(String message) {
    //Dismiss your dialog here
}

除此之外,您可以使用一些优秀的第三方库,例如EventBusOtto,这将使您的工作变得简单轻松。