0

I want to create a class which would take a phone number, send a SMS to that number and wait for answer from that specific number. Originally I planned something like this:

public class SmartSocket extends BroadcastReceiver {

    private String mPhoneNum;
    private SmartSocketMessageListener mListener;

    public SmartSocket(String phoneNum, SmartSocketMessageListener l) {
        mPhoneNum = phoneNum;
        mListener = l;
    }

    void requestStatus() {
        SmsManager smsMan = SmsManager.getDefault();
        smsMan.sendTextMessage(mPhoneNum, null, "STATUS", null, null);
    }

    public void onReceive(Context context, Intent intent) {
        //.... process received Intent, extract phone number

        if (phoneNumFrom == mPhoneNum) {
            //... we've got the answer, process it
            mListener.statusMessageReceived(messageText);
        }
    }

}

But this is not possible because Android needs an empty constructor for that class and creates a new instance every time a message is received. Is there a way around it or some pattern to achieve what I need? I want to avoid application level variables which might probably solve this problem.

Janeks Bergs
  • 224
  • 3
  • 13
  • 1
    If you register an instance of the Receiver dynamically, then you can use your constructor, but the Receiver will be tied to the `Context` it's registered on, and will die/leak when that goes away. If you want it to be "always listening", then you'll need to leave it statically registered in the manifest, somehow persist the phone number to compare - e.g., in `SharedPreferences` - and use some other mechanism to notify whichever component the `SmartSocketMessageListener` is now, be it through `startActivity()`/`startService()`, `LocalBroadcastManager`, some other sort of event bus, etc. – Mike M. Nov 05 '16 at 21:59
  • Yeah, you're right. I already digged that up in the documentation. Chose the first approach. Will put answer with code for others tomorrow. – Janeks Bergs Nov 05 '16 at 22:07

0 Answers0