简体   繁体   中英

Get message from broadcast receiver to activity

I know this question has been asked many times but still i am unable to solve my problem.I want to get the OTP from the SMS in the editText of the Activity.For this i am using broadcast receiver.

Code for broadcast receiver:

private static final String TAG = ReceiveSms.class.getSimpleName();
    private SmsReceivedListner smsReceived = null;

    @Override
    public void onReceive(Context context, Intent intent) {

                    //code to get sms....

                    Log.e(TAG, "OTP received: " + verificationCode);
                    if (smsReceived != null) {
                        smsReceived.onSmsReceived(verificationCode);
                    } else {
                        if (Constants.isLoggingEnable) {
                            Logger.logError(TAG, "Sms listner is null");

                        }
                    }

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

    public void setOnSmsReceivedListener(Context context) {
        this.smsReceived = (SmsReceivedListner) context;
    }

Activity Code

public class EnterOtp extends MasterActivity implements View.OnClickListener, OnTaskComplete, SmsReceivedListner {

    private static final String TAG = EnterOtp.class.getSimpleName();

    private Context context;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.otp);
        context = this;
        init();
    }

    private void init() {

        setUpToolbar();




        receiveSms = new ReceiveSms();
        receiveSms.setOnSmsReceivedListener(this);





    }

I have used interface but always i am getting it as null .So what can i do to get the otp.

PS- I dont want to start new Activity via intent because the activity is running only, so if via Intent can i pass the otp without starting new Activity and also maintaing the back stack as well?

If you want receive sms only when activity is running use this code:

private void init()
{
     receiveSms = new ReceiveSms();
     receiveSms.setOnSmsReceivedListener(this);
     registerReceiver(receiveSms, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}

And remove this receiver from AndroidManifest.xml

I hope it helped you.

EDIT:

In onDestroy you must use this code:

protected void onDestroy()
{
    super.onDestroy();
    // ...
    unregisterReceiver(receiveSms);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM