I tried to send an sms via an Intent with this code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("smsto:" + phoneNumber));
intent.putExtra("address", phoneNumber);
intent.putExtra("sms_body", messageBody);
intent.putExtra("exit_on_sent", true);
startActivityForResult(intent, CODE);
Then, I want to know if the SMS has been sent or not and I use this code:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case CODE:
if (resultCode == Activity.RESULT_OK)
{
//Then do...
}
elseif(resultCode == Activity.RESULT_CANCELED)
{
// Do...
}
break;
}
}
The thing is the result is always 0 (Activity.RESULT_CANCELED), even when the SMS has been sent. How can I know if the SMS has been sent or not ? I want to use the SMS default app of the phone, not create an interface that sends SMS.
In the following example, we use a
ContentObserver
to monitor updates to the SMS Provider. This Observer is created and started before the SMS Intent is fired, and checks the Provider changes against the destination address. The Activity that creates the Observer must implement theSmsSendObserver.SmsSendListener
interface to receive the callback.The Observer's constructor includes a
timeout
parameter (in milliseconds) to allow the Observer to be properly unregistered if the message is not sent after a reasonable amount of time. This can be set toNO_TIMEOUT
if desired. However, the class, as written, is meant for "one shot" use, and it will unregister itself and nullify members upon callback. Thestop()
method can be used to clean up if no callback occurs. In either case, the instance is no longer usable, and any reference to it should be set to null.Example Activity:
The
SmsSendObserver
class: