public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle data = intent.getExtras();
final 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.
Log.i("Sender id ",sender);
String messageBody = smsMessage.getMessageBody();
Log.i("get Message body ",messageBody);
messageBody=smsMessage.getDisplayMessageBody();
Log.i("Message Body ",messageBody);
//Pass on the text to our listener.
mListener.messageReceived(messageBody);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
public interface SmsListener {
public void messageReceived(String messageText);
}
in the fragement/dialog calling :
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(getContext(),"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
#Override
public void onResume() {
Log.i("In resume ","resume");
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(getContext(),"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
super.onResume();
}
#Override
public void onPause() {
Log.i("In pause ","pause");
super.onPause();
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(getContext(),"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
}
<receiver android:name="services.SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
I am not getting any error and nothing is prints in log also. Don't know what wrong going on. Even no print from the broadcast receiver. I think code in onResume is also not executing.
For Xiaomi Permission Dialog Use this Read all SMS
private void displaySmsLog() {
Uri allMessages = Uri.parse("content://sms/");
//Cursor cursor = managedQuery(allMessages, null, null, null, null); Both are same
Cursor cursor = getActivity().getContentResolver().query(allMessages, null,
null, null, null);
if (cursor!=null) {
while (cursor.moveToNext()) {
for (int i = 0; i < cursor.getColumnCount(); i++) {
Log.d(cursor.getColumnName(i) + "", cursor.getString(i) + "");
}
Log.d("One row finished",
"**************************************************");
}
}
else {
}
}
Hope this helps.:)
Since its a xiaomi device, it denies sms read/receive permission either you have to manually switch on the permission or you can try the below code just to let xiaomi know your app needs to read/receive sms and it will show a permission dialog to read sms :-
Cursor cursor = getActivity().getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
if (cursor == null) {
return;
}
try {
if (cursor.moveToFirst()) {
// must check the result to prevent exception
//This will show a permission dialog to let app read /receive sms
}
} while (cursor.moveToNext());
} else {
Log.e(this.getClass().getSimpleName(), "No SMS");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
}
Related
I am using SMS Retriever API to get OTP but the problem I am facing is that it is not receiving SMS every time. Sometime SMS content is retrieved and some time nothing happens.
I have used the Toast (Broadcaster started) to show if it is started every time but Toast is also not displayed every time. I am unable to diagnose the problem.
Broadcast Receiver code:
public class OTPBroadcastReceiver extends BroadcastReceiver {
private String otp;
private static OTPSMSReceiveListner otpsmsReceiveListner = null;
private final Pattern p = Pattern.compile("(|^)\\d{4}");
public static void injectListner(OTPSMSReceiveListner listner){
otpsmsReceiveListner = listner;
}
#Override
public void onReceive(Context context, Intent intent) {
try {
Toast.makeText(context,"Broadcaster started",Toast.LENGTH_LONG).show();
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
//Toast.makeText(context,"success",Toast.LENGTH_LONG).show();
// Get SMS message contents
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
if (message != null) {
Matcher m = p.matcher(message);
if (m.find()) {
otp = m.group(0);
}
String token;
try {
token = CommonMethods.getSecurePref("OTP", context);
} catch (Exception ex) {
token = null;
}
if (token == null) {
//Pass on the text to our listener.
otpsmsReceiveListner.onOTPReceived(otp);
}
}
break;
case CommonStatusCodes.TIMEOUT:
Log.d("onReceive", "timed out (5 minutes)");
//Toast.makeText(context,"Timeout",Toast.LENGTH_LONG).show();
otpsmsReceiveListner.onOTPTimeout();
break;
}
}
}
catch (Exception ex){
Toast.makeText(context,ex.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
}
public interface OTPSMSReceiveListner{
void onOTPReceived(String otp);
void onOTPTimeout();
}
}
OTP class:
SmsRetrieverClient client = SmsRetriever.getClient(mContext);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
try
{
Log.e("onSuccess","Successfully started retriever");
}
catch (Exception ex)
{
Log.e("onSuccess",ex.getMessage());
}
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("onFailure", "Failed to start retriever");
}
});
OTPBroadcastReceiver.injectListner(new OTPBroadcastReceiver.OTPSMSReceiveListner() {
#Override
public void onOTPReceived(String otp) {
if(otp.length() == 4) {
otpField.setText(otp);
btnVerify.performClick();
}
}
#Override
public void onOTPTimeout() {
Log.e("onOTPTimeout","onOTPTimeout");
}
});
Manifest:
<receiver
android:name=".helpers.OTPBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
</intent-filter>
</receiver>
SMS:
<#> your App OTP is:8149 585dyDy8cbh
See this answer https://stackoverflow.com/a/55374780/10449332. Please register the BroadcastReceiver inside SmsRetriever addOnSuccessListener callback.
i m trying to read OTP from message, but i cant auto read it.please tell me what i did wrong, here is my code.i m using marshmallow. thank you.
here is my SmsReceiver class:
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;
}}
here is interface
public interface SmsListener {
public void messageReceived(String messageText);
}
and this is my activity
public class MyOTP extends BaseActivity implements View.OnClickListener {
EditText txtotp;
Button btnSubmitOtp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_otp);
txtotp = (EditText) findViewById(R.id.txtOtp);
btnSubmitOtp = (Button) findViewById(R.id.btnSubmit);
btnSubmitOtp.setOnClickListener(this);
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(MyOTP.this,"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
}
}
Here is my working Broadcast receiver class which will read digits from message body & broadcast with OTP code to related class
You need to add these permissions in menifest file
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.RECEIVE_SMS" />
Here is my receiver class
public class SmsListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null) {
//---retrieve the SMS message received---
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
if (Build.VERSION.SDK_INT <= 22) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
} else {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], bundle.getString("format"));
}
msg_from = msgs[i].getOriginatingAddress();
if (msg_from.contains("PINSMS")) {
String msgBody = msgs[i].getMessageBody();
//String pinNo = msgBody.substring(msgBody.indexOf('"') + 1, msgBody.indexOf('"', msgBody.indexOf('"') + 2));
String pinNo = msgBody.replaceAll("[^0-9]", "");
Log.d("SMS", "From -" + msg_from + " : Body- " + msgBody);
//CodeVerification.insertCode(pinNo);
// Broadcast to Auto read Code sms
final String DISPLAY_MESSAGE_ACTION = context.getPackageName() + ".CodeSmsReceived";
Intent intentCodeSms = new Intent(DISPLAY_MESSAGE_ACTION);
intentCodeSms.putExtra("varificationCode", pinNo);
context.sendBroadcast(intentCodeSms);
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
I have registered this receiver in my class programmatic because i know OTP sms will come after my submit button click & i unregister it after OTP read as i dont want to trigger this receiver for every SMS by registering it in menifest.
SmsListener smsListener = new SmsListener();
try {
unregisterReceiver(smsListener);
} catch (Exception e) {
}
registerReceiver(smsListener, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
EDIT
Put below receiver in your activity to get OTP code
final String DISPLAY_MESSAGE_ACTION = activity.getPackageName() + ".CodeSmsReceived";
try {
activity.unregisterReceiver(mHandleMessageReceiver);
} catch (Exception e) {
}
activity.registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
On receiving code below method will be called
/**
* Receiving Call Log Changed broadcast
*/
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.hasExtra("varificationCode")) {
String youtOTPcode = intent.getStringExtra("varificationCode"));
}
}
};
For Marshmallow you have to ask users to give permissions. It's not given by default even if you declare it in manifest. You need to add code to get runtime permission for marshmallow devices.
For now just for checking you can go to settings --> Apps --> go to your in the list --> click on permissions --> Enable SMS permission. Then restart your app and check is it working.
Hope it will help you.
Change MyOtpActivity to
public class MyOTP extends BaseActivity{
EditText txtotp;
Button btnSubmitOtp;
private UpdateOTPReceiver mUpdateOtpReceiver;
private SMSReceiver mSmsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_otp);
txtotp = (EditText) findViewById(R.id.txtOtp);
btnSubmitOtp = (Button) findViewById(R.id.btnSubmit);
btnSubmitOtp.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
mUpdateOtpReceiver = new UpdateOTPReceiver();
registerReceiver(mUpdateOtpReceiver, new IntentFilter("UPDATE_OTP"));
registerSMSReceiver();
}
private void registerSMSReceiver() {
mSmsReceiver = new SMSReceiver();
registerReceiver(mSmsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
private class UpdateOTPReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String msg = intent.getStringExtra("msg");
Toast.makeText(MyOTP.this,"Message: "+msg,Toast.LENGTH_LONG).show();
}
}
}
}
}
In SmsReceiver
Public class SmsReceiver extends BroadcastReceiver {
#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();
//ToDo check your sender
String messageBody = smsMessage.getDisplayMessageBody();
Intent updateTokenIntent = new Intent("UPDATE_OTP");
updateTokenIntent.putExtra("msg", getVerificationCode(messageBody));
context.sendBroadcast(updateTokenIntent);
}
}
private String getVerificationCode(String message) {
if (message == null) {
return null;
}
int index = message.indexOf("is");
int index_last_length = message.indexOf(".");
if (index != -1) {
int start = index + 3;
return message.substring(start, index_last_length);
}
return null;
}
}
You Cannot Read a SMS having OTP word in it through broadcast receiver because of google policy.
You Cannot Read a SMS having OTP word in it through broadcast receiver because of google policy is well said by Ridhika....
OTP messages can only be read by app that has its HashCode in the message body.
I am trying to read incoming message using receiver.I followed tutorial and added below code but broadcast receiver is not getting fired.Log placed inside onReceive never gets fired.
Manifest
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:name=".xyz"
android:allowBackup="true"
android:icon="#mipmap/icon_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name="xyz.receiver.SmsReceiver">
<intent-filter android:priority="1">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
BroadcastReceiver
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Log.e("TEST",data.toString());
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();
String messageBody = smsMessage.getMessageBody();
mListener.messageReceived(messageBody);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
Activity
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Toast.makeText(OTPActivity.this, "Message: " + messageText, Toast.LENGTH_LONG).show();
}
});
I have used this code, hope this works for you too :)
private BroadcastReceiver mSMSReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
Log.e("sms receiver", "0000sdfghjkjhgfdsdfghjk");
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
String sms;
for (Object pdu : pdus) {
SmsMessage tmp;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
tmp = SmsMessage.createFromPdu((byte[]) pdu, bundle.getString("format"));
} else {
tmp = SmsMessage.createFromPdu((byte[]) pdu);
}
String senderMobile = tmp.getMessageBody();
sms = tmp.getMessageBody();
if (senderMobile.startsWith("کد فعالسازی شما در توپ 360:")) {
Log.e("sms receiver", "1111sdfghjkjhgfdsdfghjk");
final String mSMS = sms.replaceAll("[^0-9]", "");
//TODO Check SMS Center number with senderMobile if(senderMobile.equals(989100000)){...}
if (mSMS.length() == 5 || mSMS.length() == 6) {
Log.e("sms receiver", "2222sdfghjkjhgfdsdfghjk");
runOnUiThread(new Runnable() {
#Override
public void run() {
//CODE IS mSMS
code.setText(mSMS);
Log.e("sms receiver", "3333sdfghjkjhgfdsdfghjk");
}
});
abortBroadcast();
break;
}
}
}
}
}
} catch (Exception e) {
Log.e("sms exception", e.getMessage());
}
}
};
#Override
public void onResume() {
super.onResume();
if (isGranted) {
IntentFilter mIntentFilter = new IntentFilter();
Log.e("sms receiver", "4444sdfghjkjhgfdsdfghjk");
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
mIntentFilter.setPriority(Integer.MAX_VALUE);
registerReceiver(mSMSReceiver, mIntentFilter);
} else {
Log.e("sms receiver", "5555sdfghjkjhgfdsdfghjk");
}
}
#Override
public void onPause() {
super.onPause();
if (isRegistered) {
unregisterReceiver(mSMSReceiver);
Log.e("sms receiver", "6666sdfghjkjhgfdsdfghjk");
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 100: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isGranted = true;
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
mIntentFilter.setPriority(Integer.MAX_VALUE);
registerReceiver(mSMSReceiver, mIntentFilter);
Log.e("sms receiver", "7777sdfghjkjhgfdsdfghjk");
isRegistered = true;
onResume();
} else {
isGranted = false;
Snackbar snackbar = Snackbar.make(coordinatorLayout, "دریافت کننده خودکار پیامک غیرفعال است.", Snackbar.LENGTH_LONG);
snackbar.show();
}
return;
}
}
}
i am developing one application that is receiving sms from inbox ,i am receiving sms successfully but my requirement is receive only new(recent)message ,i do not want to read all messages from inbox ,please help me
my Code is
public class MainActivity extends Activity {
TextView showText;
StringBuilder sb = new StringBuilder();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText = (TextView)findViewById(R.id.text);
String message = getMessagess();
showText.setText(message);
}
public String getMessagess(){
Cursor cursor=null;
Uri smsuri = Uri.parse("content://sms/inbox");
try{
cursor =getContentResolver().query(smsuri, null, null, null, null);
if (cursor == null) {
// Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);
}
for(boolean
hashdata=cursor.moveToFirst();hashdata;hashdata=cursor.moveToNext()){
final String body =
cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
final String senderNo=
cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
final String date =
cursor.getString(cursor.getColumnIndexOrThrow("date"));
final String type =
cursor.getString(cursor.getColumnIndexOrThrow("type"));
if(senderNo.equals("+XXXXXXXXXX")){
for(String bd:body.split(";"))
sb.append(bd);
sb.append("\n");
}
}
if(sb==null){
sb.append("no message found");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
cursor.close();
}
return sb.toString();
}
}
For that you need to create BroadcastReceiver which receive SMS_RECEIVED broadcast and send alert to your application that New SMS has been arrieved.
Try with following code.
ReceiveSMSActivity :
public class ReceiveSMSActivity extends Activity {
public static TextView messageBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
messageBox=(TextView)findViewById(R.id.messageBox);
}
public static void updateMessageBox(String msg) {
messageBox.append(msg);
}
}
TextMessageReceiver :
public class TextMessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms) {
ReceiveSMSActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody()+"\n");
}
}
}
add this in your AndroidManifest.xml
<receiver android:name=".TextMessageReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
and this permission too
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Another SampleCode : How-to-receive-SMS
I need to develop an Android App which will receive SMS from a Specific sender, when the SMS received, the App has to get activated and gets all the values which came with the SMS, please provide me the answer?
You can use BroadcastReciver for reading sms. And extract that sms and save values in DataBase in android . When you call the first Activity check the particular value contains in the DataBase then only start the Activity.
public class ReadingMessage extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
DBAdapter dbHelper = new DBAdapter(context);
SmsMessage[] msgs = null;
String msg=null;
String str=null;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg = msgs[i].getMessageBody().toString();
str =msg.toUpperCase();
if(str.contains("your value"))
{
try{
dbHelper.open();
dbHelper.insertinfo(msg);
dbHelper.close();
}
catch(Exception e)
{
e.toString();
}
}
}
}
}
}
This code for Reading SMS.
public class StartActivity extends Activity{
private static final int ACTIVITY_REGISTRATION1=0;
private static final int ACTIVITY_SENDALERT3=1;
private static final int ACTIVITY_REGISTRATION2 = 2;
Context context;
DBAdapter dbHelper=null;
Intent intent;
String db_activation=null;
Cursor cursor;
public StartActivity()
{
this.context=this;
}
#Override
/* Method Header
* Method Name : onCreate
* Input Parameter : Bundle
* Return Value : nil
*/
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
dbHelper=new DBAdapter(this);
try
{
dbHelper.open();
cursor = dbHelper.getActivtaion();
if(cursor.getCount()==0)
{
intent=new Intent(this,Registration.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivityForResult(intent,ACTIVITY_REGISTRATION1);
}
else
{
for(int i=0;i<cursor.getCount();i++)
{
cursor.moveToNext();
db_activation = cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_ACTIVATION));
if(db_activation.equals("1"))
{
intent=new Intent(this,SendAlert.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivityForResult(intent,ACTIVITY_SENDALERT3);
}
else
{
intent=new Intent(this,Registration.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivityForResult(intent,ACTIVITY_REGISTRATION2);
}
dbHelper.close();
}
}
}
catch(Exception e)
{
finish();
System.exit(0);
e.toString();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
finish();
}
}
this code for the First Activity
public long insertTruckinfo(String db_Truckmsg)
{
ContentValues cVal=new ContentValues();
cVal.put(KEY_INFO,db_Truckmsg);
return db.insert(TRUCKINFO_TABLE, null,cVal);
}
public Cursor getActivtaion()
{
Cursor cursor =db.query(ACTIVATION_TABLE, new String[] {KEY_ID,KEY_ACTIVATION}, null,null, null, null, null);
return cursor;
}
public Cursor getTruckinfo()
{
Cursor cursor =db.query(TRUCKINFO_TABLE, new String[] {KEY_ID,KEY_INFO}, null,null, null, null, null);
return cursor;
}
This is in DataBase class.
I think thi is helpful for u....
Use a broadcast receiver to capture all the incoming messages. However, where, when and how you initialize your receiver depends on your application. You can do it on boot, or on first open of your application etc.
You will have to scan all the incoming sms, read the content, and the number and check and set a flag somewhere inside your application.