Friday 12 August 2016

Automatically Read income message to verify OTP, automatically fill in edit field and Redirect Android Studio.

Creating New Project.
Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.    
Open => app => res => layout - activity_otp.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#33cc88">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtMobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Please Enter your OTP below:"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="@color/colorText"
                android:textSize="18dp" />

            <EditText
                android:id="@+id/etOtp"
                android:layout_width="146dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:ems="10"
                android:inputType="number"
                android:background="#ffffff"
                android:paddingLeft="4dp" />

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

   

Create the Java file in project.
Open app => main => src = OtpActivity.java.

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class OtpActivity extends AppCompatActivity {
    public static EditText otpEditText;
    ProgressDialog dialog;
    public static final String KEY_OTP = "";
    String URL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otp);
        //Getting the Widget Id
        Init();
      
        //Automatically reditrect the screen

         otpEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Handler h = new Handler(Looper.getMainLooper());
                h.postDelayed(new Runnable() {
                    public void run() {
                        if (otpEditText.length() > 0) {
                            otpRegister();
                        }
                    }
                }, 6000);
            }
        });
    }

    private void Init() {
        otpEditText = (EditText) findViewById(R.id.etOtp);
    }

    private void otpRegister() {
        final String mOtp = otpEditText.getText().toString();
        //SHOWING THE DIALOG
        showDialog(true);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        Toast.makeText(OtpActivity.this, response, Toast.LENGTH_LONG).show();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
                        Toast.makeText(OtpActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(
KEY_OTP, "");
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(OtpActivity.this, "", "Sending.....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

   private void OpenScreen() {
        Intent i = new Intent(OtpActivity.this, ChooseActivtiy.class);
        startActivity(i);
    }
   //Here is fill the OTP verify code.
    public void setOtp(String otp) {

        try {
           //****Only fill here 4 digit number***//
            Pattern p = Pattern.compile("(\\d{4})");//. represents single character
            Matcher m = p.matcher(otp);
            if (m.find()) {
                String b = m.group(1);
                otpEditText.setText(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Create the Java file in project.

Open app => main => src = SmsReceiver .java.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import com.sell.vevsa.OtpActivity;


public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    try {
                        if (senderNum.equals("HP-VERIFY")) {
                            OtpActivity Sms = new OtpActivity();
                            Sms.setOtp(message);
                        }
                    } catch (Exception e) {
                    }
                }
            }

        } catch (Exception e) {

        }
    }
}


Add permission and receiver in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<receiver android:name=".SmsReceiver ">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

May this code help you. Thanks!!!!!!

No comments:

Post a Comment