-----------------------------------------manifest-----------------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.github.swarajsaaj.otpblogdemo">
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
</manifest>
--------------------------MainActivity.java--------------------------------
package io.github.swarajsaaj.otpblogdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText messageotp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageotp = (EditText) findViewById(R.id.messageotp);
SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
Log.d("Text", messageText);
Toast.makeText(MainActivity.this,"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
}
}
---------------------------SmsListener.class-------------
package io.github.swarajsaaj.otpblogdemo;
public interface SmsListener {
public void messageReceived(String messageText);
}
-----------------------------SmsReceiver.class----------------------------
package io.github.swarajsaaj.otpblogdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for(int i=0;i<pdus.length;i++){
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
//You must check here if the sender is your provider and not another one with same text.
String messageBody = smsMessage.getMessageBody();
//Pass on the text to our listener.
mListener.messageReceived(messageBody);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
No comments:
Post a Comment