android


How to dismiss progress bar once otp read from Inbox in android?


I have a Otp verification Screen in which I have a progress bar with timer ,what I want is to dismiss this progressbar once Read Otp from inbox if read successfully from Inbox then dismiss progressbar and execute Jsons Url if not then show progressbar with timer until not read sms from Inbox.for this I am using Broadcast Receiver .Kindly help me .
here is my code of 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);
}
}
}
}
and here is my BroadcastReceiver class:-
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;
}
}
Basically you want to send data from broadcast receiver to activity whenever desired message comes.you can make use of interface to communicate
In you BroadcastReceiver create interface like this
public interface OnSmsReceivedListener {
public void onSmsReceived(String message);
}
add one method to initialize interface reference
OnSmsReceivedListener smsListener;
public void setOnSmsReceivedListener(Context context) {
this.smsListener = (OnSmsReceivedListener) context;
}
use this reference to call function inside onReceive() method
smsListener.onSmsReceived("Message Received!!!");
You are done with posting data ,now give implementation of interface in your Activity and dismiss your dialog.
public class SampleActivity extends Activity implements OnSmsReceivedListener
#Override
public void onSmsReceived(String message) {
//Dismiss your dialog here
}
Other then this approach you can make use of some good third party library like EventBus and Otto which will make your work simple and easy.

Related Links

Holo Dark TabWidget style for Holo Light Theme
ListView doesn't refresh after using changeCursor() on its adapter
Android SyncAdapter Callback
External install for those Android versions that support it, but support for those that don't
Image format of the camera (Android)
How Do I Set My View LayoutParams Width Smaller?
Is it good Practice to start service every 15 minute & destroy it after sending location information in android?
How to know which View is being touched
Android ListView BUG?
Android release keystore issue: “Keystore was tampered with, or password was incorrect”
PhoneGap/Android iFrame resizing out of screen to refit contents
How to get spinner on android without xml
Keep unpressed state of a child view from a ListView item which is pressed
android application layout for android phones and tablets
Android Button and drawable area
Android how to play video using VLC Player?

Categories

HOME
service-worker
asp.net-web-api
embedded
facebook-oauth
ng-idle
angular2-material
mstest
package
solver
pclxl
yandex
cublas
hugo
jax-ws
project
watson-conversation
cmdb
google-form
nancy
favicon
frequency-distribution
shared-libraries
altera
dreamweaver
template-engine
shortest-path
ksh
aggregation
monit
interpreter
jboss6.x
apktool
winpe
xbox
hard-drive
dynamic-jasper
parse-tree
apns-php
gdata
dcmtk
naming
android-checkbox
facebook-social-plugins
xbmc
chai-as-promised
activeperl
manova
mongotemplate
zenhub
tinkerpop
avx
mathcad
branch-prediction
smartfoxserver
cronexpression
chromium-os
google-cloud-console
vulcanize
signalr.client
dup
cifilter
xdoclet
firebase-security
clipboard.js
redis-cluster
dynamics-nav-2016
phonertc
typemock
umlgraph
actionfilterattribute
grouping-sets
at-job
ghcjs
big-ip
machine-instruction
raygun
angular-carousel
malformedurlexception
tinyxml
websphere-esb
accesscontrolexception
spring-3
merb
stacky
pdfviewer
patricia-trie
jdb
fitbounds
convention
gobject-introspection
catransform3d
timthumb
msr
nhprof
load-time
cruisecontrol.rb
nstokenfield
asynchronous-wcf-call
fail-fast-fail-early
fault-tolerance
information-management

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App