How to Add a Text Message to a Messages Conversation in Android SDK
Join the DZone community and get the full member experience.
Join For Free//imports
public class SentSmsLogger extends Service {
private static final String TELEPHON_NUMBER_FIELD_NAME = "address";
private static final String MESSAGE_BODY_FIELD_NAME = "body";
private static final Uri SENT_MSGS_CONTET_PROVIDER = Uri.parse("content://sms/sent");
@Override
public void onStart(Intent intent, int startId) {
addMessageToSentIfPossible(intent);
stopSelf();
}
private void addMessageToSentIfPossible(Intent intent) {
if (intent != null) {
String telNumber = intent.getStringExtra("telNumber");
String messageBody = intent.getStringExtra("messageBody");
if (telNumber != null && messageBody != null) {
addMessageToSent(telNumber, messageBody);
}
}
}
private void addMessageToSent(String telNumber, String messageBody) {
ContentValues sentSms = new ContentValues();
sentSms.put(TELEPHON_NUMBER_FIELD_NAME, telNumber);
sentSms.put(MESSAGE_BODY_FIELD_NAME, messageBody);
ContentResolver contentResolver = getContentResolver();
contentResolver.insert(SENT_MSGS_CONTET_PROVIDER, sentSms);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
SentSmsLogger expects an Intent with receiver number and message body. Then it passes that information to proper ContentProvider. And this is the clue - it isn't well documented how to manage ContentProvider associated with messaging module. Google to the rescue ;) I've found information that relevant the ContentProvider has the URI content://sms/sent.
The next step was to find out the names of the fields that contain data about message body and its receiver. With the help of debugger, I've found them - it's body and address. I've put all of this in private constants at the top of class. That's all! Now we can use this data in a standard manner. Useful information about this can be found in the official documentation. Important note: due to compatibility issues, I've used Android SDK v. 1.5 here.
Opinions expressed by DZone contributors are their own.
Trending
-
Build a Simple Chat Server With gRPC in .Net Core
-
Why You Should Consider Using React Router V6: An Overview of Changes
-
Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
-
Building A Log Analytics Solution 10 Times More Cost-Effective Than Elasticsearch
Comments