Include android-smsmms source for modification

This commit is contained in:
Moez Bhatti
2018-01-13 00:25:53 -05:00
parent 8bb835c2f5
commit f54b3de571
332 changed files with 48979 additions and 2 deletions
@@ -0,0 +1,380 @@
package com.klinker.android.send_message;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.XmlResourceParser;
import android.os.Build;
import android.preference.PreferenceManager;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.widget.Toast;
import com.klinker.android.logger.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
public class ApnUtils {
private static final String TAG = "ApnUtils";
public static void initDefaultApns(final Context context, final OnApnFinishedListener listener) {
loadMmsSettings(context);
final ArrayList<APN> apns = loadApns(context);
if (apns == null || apns.size() == 0) {
Log.v(TAG, "Found no APNs :( Damn CDMA network probably.");
Toast.makeText(context, context.getString(R.string.auto_select_failed), Toast.LENGTH_SHORT).show();
if (listener != null) {
listener.onFinished();
}
} else if (apns.size() == 1) {
setApns(context, apns.get(0));
if (listener != null) {
listener.onFinished();
}
} else {
if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean("has_seen_select_apns_warning", false)) {
new AlertDialog.Builder(context)
.setTitle(R.string.auto_select_apn)
.setMessage(R.string.auto_select_multiple_apns)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int num) {
showApnChooser(context, apns, listener);
}
})
.show();
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("has_seen_select_apns_warning", true).commit();
} else {
showApnChooser(context, apns, listener);
}
}
}
private static void showApnChooser(final Context context, final ArrayList<APN> apns, final OnApnFinishedListener listener) {
CharSequence[] items = new CharSequence[apns.size()];
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String curMmsc = sharedPrefs.getString("mmsc_url", "");
String curProxy = sharedPrefs.getString("mms_proxy", "");
String curPort = sharedPrefs.getString("mms_port", "");
int defaultApn = -1;
for (int i = 0; i < items.length; i++) {
APN apn = apns.get(i);
items[i] = (i+1) + ". " + apn.name;
if (apn.mmsc.equals(curMmsc) && apn.proxy.equals(curProxy) && apn.port.equals(curPort)) {
defaultApn = i;
}
}
new AlertDialog.Builder(context)
.setSingleChoiceItems(items, defaultApn, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
setApns(context, apns.get(i));
if (listener != null) {
listener.onFinished();
}
dialogInterface.dismiss();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
if (listener != null) {
listener.onFinished();
}
}
})
.show();
}
public interface OnApnFinishedListener {
public abstract void onFinished();
}
private static void loadMmsSettings(Context context) {
XmlResourceParser parser = context.getResources().getXml(R.xml.mms_config);
String maxMessageSize = 1000000 + "";
int maxImageHeight = 800;
int maxImageWidth = 800;
String userAgent = "Android Messaging";
String uaProfUrl = "http://www.gstatic.com/android/hangouts/hangouts_mms_ua_profile.xml";
try {
beginDocument(parser, "mms_config");
while (true) {
nextElement(parser);
String tag = parser.getName();
if (tag == null) {
break;
}
String name = parser.getAttributeName(0);
String value = parser.getAttributeValue(0);
String text = null;
if (parser.next() == XmlPullParser.TEXT) {
text = parser.getText();
}
Log.v(TAG, "tag: " + tag + " value: " + value + " - " +
text);
if ("name".equalsIgnoreCase(name)) {
if ("int".equals(tag)) {
// int config tags go here
if ("maxMessageSize".equalsIgnoreCase(value)) {
maxMessageSize = text;
} else if ("maxImageHeight".equalsIgnoreCase(value)) {
maxImageHeight = Integer.parseInt(text);
} else if ("maxImageWidth".equalsIgnoreCase(value)) {
maxImageWidth = Integer.parseInt(text);
}
} else if ("string".equals(tag)) {
// string config tags go here
if ("userAgent".equalsIgnoreCase(value)) {
userAgent = text;
} else if ("uaProfUrl".equalsIgnoreCase(value)) {
uaProfUrl = text;
}
}
}
}
} catch (XmlPullParserException e) {
Log.e(TAG, "loadMmsSettings caught ", e);
} catch (NumberFormatException e) {
Log.e(TAG, "loadMmsSettings caught ", e);
} catch (IOException e) {
Log.e(TAG, "loadMmsSettings caught ", e);
} finally {
parser.close();
}
String errorStr = null;
if (errorStr != null) {
String err =
String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting",
errorStr);
Log.e(TAG, err);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
userAgent = telephonyManager.getMmsUserAgent();
uaProfUrl = telephonyManager.getMmsUAProfUrl();
}
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putInt("mms_max_width", maxImageWidth)
.putInt("mms_max_height", maxImageHeight)
.putString("mms_max_size", maxMessageSize)
.putString("mms_agent", userAgent)
.putString("mms_user_agent_profile_url", uaProfUrl)
.commit();
}
private static ArrayList<APN> loadApns(Context context) {
XmlResourceParser parser = context.getResources().getXml(R.xml.apns);
ArrayList<APN> apns = new ArrayList<APN>();
String mmsc = "", proxy = "", port = "", carrier = "";
int mcc = -1, mnc = -1;
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = manager.getNetworkOperator();
if (isValidNetworkOperator(networkOperator)) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
String s = networkOperator.substring(3);
try {
mnc = Integer.parseInt(s.replaceFirst("^0{1,2}", ""));
} catch (Exception e) {
mnc = -1;
}
} else {
mcc = context.getResources().getConfiguration().mcc;
mnc = context.getResources().getConfiguration().mnc;
}
try {
if (mcc == -1) {
mcc = Integer.parseInt(new ServiceState().getOperatorNumeric().substring(0, 3));
}
if (mnc == -1) {
TelephonyManager tm = (TelephonyManager) context.getSystemService
(Context.TELEPHONY_SERVICE);
mnc = ((CdmaCellLocation) tm.getCellLocation()).getSystemId();
}
} catch (Exception e) {
}
if (mcc == -1 || mnc == -1) {
Log.v(TAG, "couldn't find both mcc and mnc. mcc = " + mcc + ", mnc = " + mnc);
return null;
}
Log.v(TAG, "mcc: " + mcc + " mnc: " + mnc);
try {
beginDocument(parser, "apns");
while (true) {
nextElement(parser);
String tag = parser.getName();
if (tag == null) {
break;
}
boolean mccCorrect = false, mncCorrect = false;
for (int i = 0; i < parser.getAttributeCount(); i++) {
try {
String name = parser.getAttributeName(i);
int value = Integer.parseInt(parser.getAttributeValue(i));
if ("mcc".equals(name) && mcc == value) {
mccCorrect = true;
} else if ("mnc".equals(name) && mnc == value) {
mncCorrect = true;
}
} catch (Exception e) {
// cast exception probably
}
}
if (mccCorrect && mncCorrect) {
// parse the rest of the apn
for (int i = 0; i < parser.getAttributeCount(); i++) {
String name = parser.getAttributeName(i);
String value = parser.getAttributeValue(i);
if ("type".equals(name)) {
if (!value.contains("mms")) {
mmsc = "";
proxy = "";
port = "";
break;
}
} else if ("mmsc".equals(name)) {
mmsc = value;
} else if ("mmsproxy".equals(name)) {
proxy = value;
} else if ("mmsport".equals(name)) {
port = value;
} else if ("carrier".equals(name)) {
carrier = value;
} else if ("port".equals(name) && port.equals("")) {
port = value;
}
}
if (!mmsc.equals("")) {
APN apn = new APN();
apn.name = carrier;
apn.mmsc = mmsc;
apn.proxy = proxy;
apn.port = port;
boolean contains = false;
for (int i = 0; i < apns.size(); i++) {
APN current = apns.get(i);
if (current.mmsc.equals(apn.mmsc) && current.port.equals(apn.port) && current.proxy.equals(apn.proxy)) {
contains = true;
break;
}
}
if (!contains) {
apns.add(apn);
}
}
}
}
} catch (XmlPullParserException e) {
Log.e(TAG, "loadApns caught ", e);
} catch (NumberFormatException e) {
Log.e(TAG, "loadApns caught ", e);
} catch (IOException e) {
Log.e(TAG, "loadApns caught ", e);
} finally {
parser.close();
}
Log.v(TAG, "MMSC: " + mmsc + ", MMS Proxy: " + proxy + ", MMS Port: " + port);
String errorStr = null;
if (errorStr != null) {
String err =
String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting",
errorStr);
Log.e(TAG, err);
}
return apns;
}
/**
* Checks if the given network operator is valid, i.e. it's not null, empty or contains "null"
*
* @param networkOperator
* The network operator to be checked
*
* @return True if is a valid operator
*/
private static boolean isValidNetworkOperator(String networkOperator) {
return networkOperator != null && !networkOperator.isEmpty() &&
!networkOperator.contains("null");
}
private static void setApns(Context context, APN apn) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString("mmsc_url", apn.mmsc)
.putString("mms_proxy", apn.proxy)
.putString("mms_port", apn.port)
.commit();
}
private static void beginDocument(XmlPullParser parser, String firstElementName) throws XmlPullParserException, IOException {
int type;
while ((type=parser.next()) != parser.START_TAG
&& type != parser.END_DOCUMENT) {
;
}
if (type != parser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
if (!parser.getName().equals(firstElementName)) {
throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
", expected " + firstElementName);
}
}
private static void nextElement(XmlPullParser parser) throws XmlPullParserException, IOException {
int type;
while ((type=parser.next()) != parser.START_TAG
&& type != parser.END_DOCUMENT) {
;
}
}
private static class APN {
public String name;
public String mmsc;
public String proxy;
public String port;
}
}
@@ -0,0 +1,41 @@
package com.klinker.android.send_message;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* Utility for helping with Android O changes. This means that we need to explicitly send broadcasts
* to the correct receiver instead of implicitly. This is done by attaching the class and package
* name to the intent based on the provided action.
*/
public class BroadcastUtils {
public static void sendExplicitBroadcast(Context context, Intent intent, String action) {
addClassName(context, intent, action);
intent.setAction(action);
context.sendBroadcast(intent);
}
public static void addClassName(Context context, Intent intent, String action) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo packageInfo =
pm.getPackageInfo(context.getPackageName(), PackageManager.GET_RECEIVERS);
ActivityInfo[] receivers = packageInfo.receivers;
for (ActivityInfo receiver : receivers) {
if (receiver.taskAffinity.equals(action)) {
intent.setClassName(receiver.packageName, receiver.name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
intent.setPackage(context.getPackageName());
}
}
@@ -0,0 +1,114 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import com.klinker.android.logger.Log;
import java.util.Calendar;
public class DeliveredReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("delivery_receiver", "marking message as delivered");
Uri uri;
try {
uri = Uri.parse(intent.getStringExtra("message_uri"));
if (uri.equals("")) {
uri = null;
}
} catch (Exception e) {
uri = null;
}
switch (getResultCode()) {
case Activity.RESULT_OK:
// notify user that message was delivered
Intent delivered = new Intent(Transaction.NOTIFY_OF_DELIVERY);
delivered.putExtra("result", true);
delivered.putExtra("message_uri", uri == null ? "" : uri.toString());
BroadcastUtils.sendExplicitBroadcast(
context, delivered, Transaction.NOTIFY_OF_DELIVERY);
if (uri != null) {
ContentValues values = new ContentValues();
values.put("status", "0");
values.put("date_sent", Calendar.getInstance().getTimeInMillis());
values.put("read", true);
context.getContentResolver().update(uri, values, null, null);
} else {
Cursor query = context.getContentResolver().query(Uri.parse("content://sms/sent"), null, null, null, "date desc");
// mark message as delivered in database
if (query.moveToFirst()) {
String id = query.getString(query.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("status", "0");
values.put("date_sent", Calendar.getInstance().getTimeInMillis());
values.put("read", true);
context.getContentResolver().update(Uri.parse("content://sms/sent"), values, "_id=" + id, null);
}
query.close();
}
break;
case Activity.RESULT_CANCELED:
// notify user that message failed to be delivered
Intent notDelivered = new Intent(Transaction.NOTIFY_OF_DELIVERY);
notDelivered.putExtra("result", false);
notDelivered.putExtra("message_uri", uri == null ? "" : uri.toString());
BroadcastUtils.sendExplicitBroadcast(
context, notDelivered, Transaction.NOTIFY_OF_DELIVERY);
if (uri != null) {
ContentValues values = new ContentValues();
values.put("status", "64");
values.put("date_sent", Calendar.getInstance().getTimeInMillis());
values.put("read", true);
values.put("error_code", getResultCode());
context.getContentResolver().update(uri, values, null, null);
} else {
Cursor query2 = context.getContentResolver().query(Uri.parse("content://sms/sent"), null, null, null, "date desc");
// mark failed in database
if (query2.moveToFirst()) {
String id = query2.getString(query2.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("status", "64");
values.put("read", true);
values.put("error_code", getResultCode());
context.getContentResolver().update(Uri.parse("content://sms/sent"), values, "_id=" + id, null);
}
query2.close();
}
break;
}
BroadcastUtils.sendExplicitBroadcast(context, new Intent(), Transaction.REFRESH);
}
}
@@ -0,0 +1,537 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.graphics.Bitmap;
import com.klinker.android.logger.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Class to hold all relevant message information to send
*
* @author Jake Klinker
*/
public class Message {
public static final class Part {
private byte[] media;
private String contentType;
private String name;
public Part(byte[] media, String contentType, String name) {
this.media = media;
this.contentType = contentType;
this.name = name;
}
public byte[] getMedia() {
return media;
}
public String getContentType() {
return contentType;
}
public String getName() {
return name;
}
}
private String text;
private String subject;
private String[] addresses;
private Bitmap[] images;
private String[] imageNames;
private List<Part> parts = new ArrayList<Part>();
private boolean save;
private int delay;
/**
* Default constructor
*/
public Message() {
this("", new String[]{""});
}
/**
* Constructor
*
* @param text is the message to send
* @param address is the phone number to send to
*/
public Message(String text, String address) {
this(text, address.trim().split(" "));
}
/**
* Constructor
*
* @param text is the message to send
* @param address is the phone number to send to
* @param subject is the subject of the mms message
*/
public Message(String text, String address, String subject) {
this(text, address.trim().split(" "), subject);
}
/**
* Constructor
*
* @param text is the message to send
* @param addresses is an array of phone numbers to send to
*/
public Message(String text, String[] addresses) {
this.text = text;
this.addresses = addresses;
this.images = new Bitmap[0];
this.subject = null;
this.save = true;
this.delay = 0;
}
/**
* Constructor
*
* @param text is the message to send
* @param addresses is an array of phone numbers to send to
* @param subject is the subject of the mms message
*/
public Message(String text, String[] addresses, String subject) {
this.text = text;
this.addresses = addresses;
this.images = new Bitmap[0];
this.subject = subject;
this.save = true;
this.delay = 0;
}
/**
* Constructor
*
* @param text is the message to send
* @param address is the phone number to send to
* @param image is the image that you want to send
*/
public Message(String text, String address, Bitmap image) {
this(text, address.trim().split(" "), new Bitmap[]{image});
}
/**
* Constructor
*
* @param text is the message to send
* @param address is the phone number to send to
* @param image is the image that you want to send
* @param subject is the subject of the mms message
*/
public Message(String text, String address, Bitmap image, String subject) {
this(text, address.trim().split(" "), new Bitmap[]{image}, subject);
}
/**
* Constructor
*
* @param text is the message to send
* @param addresses is an array of phone numbers to send to
* @param image is the image that you want to send
*/
public Message(String text, String[] addresses, Bitmap image) {
this(text, addresses, new Bitmap[]{image});
}
/**
* Constructor
*
* @param text is the message to send
* @param addresses is an array of phone numbers to send to
* @param image is the image that you want to send
* @param subject is the subject of the mms message
*/
public Message(String text, String[] addresses, Bitmap image, String subject) {
this(text, addresses, new Bitmap[]{image}, subject);
}
/**
* Constructor
*
* @param text is the message to send
* @param address is the phone number to send to
* @param images is an array of images that you want to send
*/
public Message(String text, String address, Bitmap[] images) {
this(text, address.trim().split(" "), images);
}
/**
* Constructor
*
* @param text is the message to send
* @param address is the phone number to send to
* @param images is an array of images that you want to send
* @param subject is the subject of the mms message
*/
public Message(String text, String address, Bitmap[] images, String subject) {
this(text, address.trim().split(" "), images, subject);
}
/**
* Constructor
*
* @param text is the message to send
* @param addresses is an array of phone numbers to send to
* @param images is an array of images that you want to send
*/
public Message(String text, String[] addresses, Bitmap[] images) {
this.text = text;
this.addresses = addresses;
this.images = images;
this.subject = null;
this.save = true;
this.delay = 0;
}
/**
* Constructor
*
* @param text is the message to send
* @param addresses is an array of phone numbers to send to
* @param images is an array of images that you want to send
* @param subject is the subject of the mms message
*/
public Message(String text, String[] addresses, Bitmap[] images, String subject) {
this.text = text;
this.addresses = addresses;
this.images = images;
this.subject = subject;
this.save = true;
this.delay = 0;
}
/**
* Sets the message
*
* @param text is the string to set message to
*/
public void setText(String text) {
this.text = text;
}
/**
* Sets recipients
*
* @param addresses is the array of recipients to send to
*/
public void setAddresses(String[] addresses) {
this.addresses = addresses;
}
/**
* Sets single recipient
*
* @param address is the phone number of the recipient
*/
public void setAddress(String address) {
this.addresses = new String[1];
this.addresses[0] = address;
}
/**
* Sets images
*
* @param images is the array of images to send to recipient
*/
public void setImages(Bitmap[] images) {
this.images = images;
}
/**
* Sets image names
*
* @param names
*/
public void setImageNames(String[] names) {
this.imageNames = names;
}
/**
* Sets image
*
* @param image is the single image to send to recipient
*/
public void setImage(Bitmap image) {
this.images = new Bitmap[1];
this.images[0] = image;
}
/**
* Sets audio file. Must be in wav format.
*
* @param audio is the single audio sample to send to recipient
*/
@Deprecated
public void setAudio(byte[] audio) {
addAudio(audio);
}
/**
* Sets audio file. Must be in wav format.
*
* @param audio is the single audio sample to send to recipient
*/
public void addAudio(byte[] audio) {
addAudio(audio, null);
}
/**
* Sets audio file. Must be in wav format.
*
* @param audio is the single audio sample to send to recipient
* @param name is the name of the file
*/
public void addAudio(byte[] audio, String name) {
addMedia(audio, "audio/wav", name);
}
/**
* Sets video file
*
* @param video is the single video sample to send to recipient
*/
@Deprecated
public void setVideo(byte[] video) {
addVideo(video);
}
/**
* Adds video file
*
* @param video is the single video sample to send to recipient
*/
public void addVideo(byte[] video) {
addVideo(video, null);
}
/**
* Adds video file
*
* @param video is the single video sample to send to recipient
* @param name is the name of the video file
*/
public void addVideo(byte[] video, String name) {
addMedia(video, "video/3gpp", name);
}
/**
* Sets other media
*
* @param media is the media you want to send
* @param mimeType is the mimeType of the media
*/
@Deprecated
public void setMedia(byte[] media, String mimeType) {
addMedia(media, mimeType);
}
/**
* Adds other media
*
* @param media is the media you want to send
* @param mimeType is the mimeType of the media
*/
public void addMedia(byte[] media, String mimeType) {
this.parts.add(new Part(media, mimeType, null));
}
/**
* Adds other media
*
* @param media is the media you want to send
* @param mimeType is the mimetype of the media
* @param name is the name of the file
*/
public void addMedia(byte[] media, String mimeType, String name) {
this.parts.add(new Part(media, mimeType, name));
}
/**
* Sets the subject
*
* @param subject is the subject of the mms message
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* Sets whether or not to save a message to the database
*
* @param save is whether or not to save the message
*/
public void setSave(boolean save) {
this.save = save;
}
/**
* Sets the time delay before sending a message
* NOTE: this is only applicable for SMS messages
*
* @param delay the time delay in milliseconds
*/
public void setDelay(int delay) {
this.delay = delay;
}
/**
* Method to add another recipient to the object
*
* @param address is the string of the recipients phone number to add to end of recipients array
*/
public void addAddress(String address) {
String[] temp = this.addresses;
if (temp == null) {
temp = new String[0];
}
this.addresses = new String[temp.length + 1];
for (int i = 0; i < temp.length; i++) {
this.addresses[i] = temp[i];
}
this.addresses[temp.length] = address;
}
/**
* Add another image to the object
*
* @param image is the image that you want to add to the end of the bitmaps array
*/
public void addImage(Bitmap image) {
Bitmap[] temp = this.images;
if (temp == null) {
temp = new Bitmap[0];
}
this.images = new Bitmap[temp.length + 1];
for (int i = 0; i < temp.length; i++) {
this.images[i] = temp[i];
}
this.images[temp.length] = image;
}
/**
* Gets the text of the message to send
*
* @return the string of the message to send
*/
public String getText() {
return this.text;
}
/**
* Gets the addresses of the message
*
* @return an array of strings with all of the addresses
*/
public String[] getAddresses() {
return this.addresses;
}
/**
* Gets the images in the message
*
* @return an array of bitmaps with all of the images
*/
public Bitmap[] getImages() {
return this.images;
}
/**
* Gets image names for the message
*
* @return
*/
public String[] getImageNames() {
return this.imageNames;
}
/**
* Gets the audio sample in the message
*
* @return an array of bytes with audio information for the message
*/
public List<Part> getParts() {
return this.parts;
}
/**
* Gets the subject of the mms message
*
* @return a string with the subject of the message
*/
public String getSubject() {
return this.subject;
}
/**
* Gets whether or not to save the message to the database
*
* @return a boolean of whether or not to save
*/
public boolean getSave() {
return this.save;
}
/**
* Gets the time to delay before sending the message
*
* @return the delay time in milliseconds
*/
public int getDelay() {
return this.delay;
}
/**
* Static method to convert a bitmap into a byte array to easily send it over http
*
* @param image is the image to convert
* @return a byte array of the image data
*/
public static byte[] bitmapToByteArray(Bitmap image) {
byte[] output = new byte[0];
if (image == null) {
Log.v("Message", "image is null, returning byte array of size 0");
return output;
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
image.compress(Bitmap.CompressFormat.JPEG, 90, stream);
output = stream.toByteArray();
} finally {
try {
stream.close();
} catch (IOException e) {}
}
return output;
}
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import java.io.File;
import java.io.FileNotFoundException;
public class MmsFileProvider extends ContentProvider {
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Don't support queries.
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// Don't support inserts.
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Don't support deletes.
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// Don't support updates.
return 0;
}
@Override
public String getType(Uri uri) {
// For this sample, assume all files have no type.
return null;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String fileMode) throws FileNotFoundException {
File file = new File(getContext().getCacheDir(), uri.getPath());
int mode = (TextUtils.equals(fileMode, "r") ? ParcelFileDescriptor.MODE_READ_ONLY :
ParcelFileDescriptor.MODE_WRITE_ONLY
|ParcelFileDescriptor.MODE_TRUNCATE
|ParcelFileDescriptor.MODE_CREATE);
return ParcelFileDescriptor.open(file, mode);
}
}
@@ -0,0 +1,379 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.util.Log;
import com.android.mms.service_alt.DownloadRequest;
import com.android.mms.service_alt.MmsConfig;
import com.android.mms.transaction.DownloadManager;
import com.android.mms.transaction.HttpUtils;
import com.android.mms.transaction.TransactionSettings;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.InvalidHeaderValueException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.NotifyRespInd;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.google.android.mms.util_alt.SqliteWrapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_RETRIEVED;
public class MmsReceivedReceiver extends BroadcastReceiver {
private static final String TAG = "MmsReceivedReceiver";
public static final String MMS_RECEIVED = "com.klinker.android.messaging.MMS_RECEIVED";
public static final String EXTRA_FILE_PATH = "file_path";
public static final String EXTRA_LOCATION_URL = "location_url";
public static final String EXTRA_TRIGGER_PUSH = "trigger_push";
public static final String EXTRA_URI = "notification_ind_uri";
private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
private static final ExecutorService RECEIVE_NOTIFICATION_EXECUTOR = Executors.newSingleThreadExecutor();
public MmscInformation getMmscInfoForReceptionAck() {
// Override this and provide the MMSC to send the ACK to.
// some carriers will download duplicate MMS messages without this ACK. When using the
// system sending method, apparently Google does not do this for us. Not sure why.
// You might have to have users manually enter their APN settings if you cannot get them
// from the system somehow.
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "MMS has finished downloading, persisting it to the database");
String path = intent.getStringExtra(EXTRA_FILE_PATH);
Log.v(TAG, path);
FileInputStream reader = null;
Uri messageUri = null;
String errorMessage = null;
try {
File mDownloadFile = new File(path);
final int nBytes = (int) mDownloadFile.length();
reader = new FileInputStream(mDownloadFile);
final byte[] response = new byte[nBytes];
reader.read(response, 0, nBytes);
List<CommonAsyncTask> tasks = getNotificationTask(context, intent, response);
messageUri = DownloadRequest.persist(context, response,
new MmsConfig.Overridden(new MmsConfig(context), null),
intent.getStringExtra(EXTRA_LOCATION_URL),
Utils.getDefaultSubscriptionId(), null);
Log.v(TAG, "response saved successfully");
Log.v(TAG, "response length: " + response.length);
mDownloadFile.delete();
if (tasks != null) {
Log.v(TAG, "running the common async notifier for download");
for (CommonAsyncTask task : tasks)
task.executeOnExecutor(RECEIVE_NOTIFICATION_EXECUTOR);
}
} catch (FileNotFoundException e) {
errorMessage = "MMS received, file not found exception";
Log.e(TAG, errorMessage, e);
} catch (IOException e) {
errorMessage = "MMS received, io exception";
Log.e(TAG, errorMessage, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
errorMessage = "MMS received, io exception";
Log.e(TAG, "MMS received, io exception", e);
}
}
}
handleHttpError(context, intent);
DownloadManager.finishDownload(intent.getStringExtra(EXTRA_LOCATION_URL));
if (messageUri != null) {
onMessageReceived(messageUri);
}
if (errorMessage != null) {
onError(errorMessage);
}
}
protected void onMessageReceived(Uri messageUri) {
// Override this in a custom receiver, if you want access to the message, outside of the
// internal SMS/MMS database
}
protected void onError(String error) {
}
private void handleHttpError(Context context, Intent intent) {
final int httpError = intent.getIntExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, 0);
if (httpError == 404 ||
httpError == 400) {
// Delete the corresponding NotificationInd
SqliteWrapper.delete(context,
context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
intent.getStringExtra(EXTRA_LOCATION_URL)
});
}
}
private static NotificationInd getNotificationInd(Context context, Intent intent) throws MmsException {
return (NotificationInd) PduPersister.getPduPersister(context).load((Uri) intent.getParcelableExtra(EXTRA_URI));
}
private static abstract class CommonAsyncTask extends AsyncTask<Void, Void, Void> {
protected final Context mContext;
protected final TransactionSettings mTransactionSettings;
final NotificationInd mNotificationInd;
final String mContentLocation;
CommonAsyncTask(Context context, TransactionSettings settings, NotificationInd ind) {
mContext = context;
mTransactionSettings = settings;
mNotificationInd = ind;
mContentLocation = new String(ind.getContentLocation());
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
byte[] sendPdu(byte[] pdu, String mmscUrl) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu, mmscUrl);
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
byte[] sendPdu(byte[] pdu) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu,
mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
private byte[] sendPdu(long token, byte[] pdu,
String mmscUrl) throws IOException, MmsException {
if (pdu == null) {
throw new MmsException();
}
if (mmscUrl == null) {
throw new IOException("Cannot establish route: mmscUrl is null");
}
if (com.android.mms.transaction.Transaction.useWifi(mContext)) {
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
false, null, 0);
}
Utils.ensureRouteToHost(mContext, mmscUrl, mTransactionSettings.getProxyAddress());
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
}
private static class NotifyRespTask extends CommonAsyncTask {
NotifyRespTask(Context context, NotificationInd ind, TransactionSettings settings) {
super(context, settings, ind);
}
@Override
protected Void doInBackground(Void... params) {
// Create the M-NotifyResp.ind
NotifyRespInd notifyRespInd = null;
try {
notifyRespInd = new NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.getTransactionId(),
STATUS_RETRIEVED);
// Pack M-NotifyResp.ind and send it
if(com.android.mms.MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, notifyRespInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, notifyRespInd).make());
}
} catch (MmsException e) {
Log.e(TAG, "error", e);
} catch (IOException e) {
Log.e(TAG, "error", e);
}
return null;
}
}
private static class AcknowledgeIndTask extends CommonAsyncTask {
private final RetrieveConf mRetrieveConf;
AcknowledgeIndTask(Context context, NotificationInd ind, TransactionSettings settings, RetrieveConf rc) {
super(context, settings, ind);
mRetrieveConf = rc;
}
@Override
protected Void doInBackground(Void... params) {
// Send M-Acknowledge.ind to MMSC if required.
// If the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK.
byte[] tranId = mRetrieveConf.getTransactionId();
if (tranId != null) {
Log.v(TAG, "sending ACK to MMSC: " + mTransactionSettings.getMmscUrl());
// Create M-Acknowledge.ind
com.google.android.mms.pdu_alt.AcknowledgeInd acknowledgeInd = null;
try {
acknowledgeInd = new com.google.android.mms.pdu_alt.AcknowledgeInd(
PduHeaders.CURRENT_MMS_VERSION, tranId);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
acknowledgeInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-Acknowledge.ind and send it
if(com.android.mms.MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, acknowledgeInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, acknowledgeInd).make());
}
} catch (InvalidHeaderValueException e) {
Log.e(TAG, "error", e);
} catch (MmsException e) {
Log.e(TAG, "error", e);
} catch (IOException e) {
Log.e(TAG, "error", e);
}
}
return null;
}
}
private List<CommonAsyncTask> getNotificationTask(Context context, Intent intent, byte[] response) {
if (response.length == 0) {
Log.v(TAG, "MmsReceivedReceiver.sendNotification blank response");
return null;
}
if (getMmscInfoForReceptionAck() == null) {
Log.v(TAG, "No MMSC information set, so no notification tasks will be able to complete");
return null;
}
final GenericPdu pdu =
(new PduParser(response, new MmsConfig.Overridden(new MmsConfig(context), null).
getSupportMmsContentDisposition())).parse();
if (pdu == null || !(pdu instanceof RetrieveConf)) {
android.util.Log.e(TAG, "MmsReceivedReceiver.sendNotification failed to parse pdu");
return null;
}
try {
final NotificationInd ind = getNotificationInd(context, intent);
final MmscInformation mmsc = getMmscInfoForReceptionAck();
final TransactionSettings transactionSettings = new TransactionSettings(mmsc.mmscUrl, mmsc.mmsProxy, mmsc.proxyPort);
final List<CommonAsyncTask> responseTasks = new ArrayList<>();
responseTasks.add(new AcknowledgeIndTask(context, ind, transactionSettings, (RetrieveConf) pdu));
responseTasks.add(new NotifyRespTask(context, ind, transactionSettings));
return responseTasks;
} catch (MmsException e) {
Log.e(TAG, "error", e);
return null;
}
}
public static class MmscInformation {
String mmscUrl;
String mmsProxy;
int proxyPort;
public MmscInformation(String mmscUrl, String mmsProxy, int proxyPort) {
this.mmscUrl = mmscUrl;
this.mmsProxy = mmsProxy;
this.proxyPort = proxyPort;
}
}
}
@@ -0,0 +1,322 @@
package com.klinker.android.send_message;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Telephony;
import android.telephony.SmsManager;
import com.android.mms.service_alt.DownloadRequest;
import com.android.mms.service_alt.MmsConfig;
import com.android.mms.transaction.DownloadManager;
import com.android.mms.transaction.HttpUtils;
import com.android.mms.transaction.TransactionSettings;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.InvalidHeaderValueException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.NotifyRespInd;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.logger.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_RETRIEVED;
import static com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_FILE_PATH;
import static com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_LOCATION_URL;
import static com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_TRIGGER_PUSH;
import static com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_URI;
public class MmsReceivedService extends IntentService {
private static final String TAG = "MmsReceivedService";
private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
public MmsReceivedService() {
super("MmsReceivedService");
}
public MmsReceivedService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.v(TAG, "MMS has finished downloading, persisting it to the database");
String path = intent.getStringExtra(EXTRA_FILE_PATH);
Log.v(TAG, path);
FileInputStream reader = null;
try {
File mDownloadFile = new File(path);
final int nBytes = (int) mDownloadFile.length();
reader = new FileInputStream(mDownloadFile);
final byte[] response = new byte[nBytes];
reader.read(response, 0, nBytes);
CommonNotificationTask task = getNotificationTask(this, intent, response);
executeNotificationTask(task);
DownloadRequest.persist(this, response,
new MmsConfig.Overridden(new MmsConfig(this), null),
intent.getStringExtra(EXTRA_LOCATION_URL),
Utils.getDefaultSubscriptionId(), null);
Log.v(TAG, "response saved successfully");
Log.v(TAG, "response length: " + response.length);
mDownloadFile.delete();
} catch (FileNotFoundException e) {
Log.e(TAG, "MMS received, file not found exception", e);
} catch (IOException e) {
Log.e(TAG, "MMS received, io exception", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, "MMS received, io exception", e);
}
}
handleHttpError(this, intent);
DownloadManager.finishDownload(intent.getStringExtra(EXTRA_LOCATION_URL));
}
}
private static void handleHttpError(Context context, Intent intent) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
final int httpError = intent.getIntExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, 0);
if (httpError == 404 ||
httpError == 400) {
// Delete the corresponding NotificationInd
SqliteWrapper.delete(context,
context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
intent.getStringExtra(EXTRA_LOCATION_URL)
});
}
}
private static NotificationInd getNotificationInd(Context context, Intent intent) throws MmsException {
return (NotificationInd) PduPersister.getPduPersister(context).load((Uri) intent.getParcelableExtra(EXTRA_URI));
}
private static abstract class CommonNotificationTask {
protected final Context mContext;
private final TransactionSettings mTransactionSettings;
final NotificationInd mNotificationInd;
final String mContentLocation;
CommonNotificationTask(Context context, TransactionSettings settings, NotificationInd ind) {
mContext = context;
mTransactionSettings = settings;
mNotificationInd = ind;
mContentLocation = new String(ind.getContentLocation());
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
byte[] sendPdu(byte[] pdu, String mmscUrl) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu, mmscUrl);
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
byte[] sendPdu(byte[] pdu) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu,
mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
private byte[] sendPdu(final long token, final byte[] pdu,
final String mmscUrl) throws IOException, MmsException {
if (pdu == null) {
throw new MmsException();
}
if (mmscUrl == null) {
throw new IOException("Cannot establish route: mmscUrl is null");
}
if (com.android.mms.transaction.Transaction.useWifi(mContext)) {
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
false, null, 0);
}
return Utils.ensureRouteToMmsNetwork(mContext, mmscUrl, mTransactionSettings.getProxyAddress(), new Utils.Task<byte[]>() {
@Override
public byte[] run() throws IOException {
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
});
}
public abstract void run() throws IOException;
}
private static class NotifyRespTask extends CommonNotificationTask {
NotifyRespTask(Context context, NotificationInd ind, TransactionSettings settings) {
super(context, settings, ind);
}
@Override
public void run() throws IOException {
// Create the M-NotifyResp.ind
NotifyRespInd notifyRespInd = null;
try {
notifyRespInd = new NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.getTransactionId(),
STATUS_RETRIEVED);
// Pack M-NotifyResp.ind and send it
if(com.android.mms.MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, notifyRespInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, notifyRespInd).make());
}
} catch (MmsException e) {
Log.e(TAG, "error", e);
}
}
}
private static class AcknowledgeIndTask extends CommonNotificationTask {
private final RetrieveConf mRetrieveConf;
AcknowledgeIndTask(Context context, NotificationInd ind, TransactionSettings settings, RetrieveConf rc) {
super(context, settings, ind);
mRetrieveConf = rc;
}
@Override
public void run() throws IOException {
// Send M-Acknowledge.ind to MMSC if required.
// If the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK.
byte[] tranId = mRetrieveConf.getTransactionId();
if (tranId != null) {
// Create M-Acknowledge.ind
com.google.android.mms.pdu_alt.AcknowledgeInd acknowledgeInd = null;
try {
acknowledgeInd = new com.google.android.mms.pdu_alt.AcknowledgeInd(
PduHeaders.CURRENT_MMS_VERSION, tranId);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
acknowledgeInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-Acknowledge.ind and send it
if(com.android.mms.MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, acknowledgeInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, acknowledgeInd).make());
}
} catch (InvalidHeaderValueException e) {
Log.e(TAG, "error", e);
} catch (MmsException e) {
Log.e(TAG, "error", e);
}
}
}
}
private static CommonNotificationTask getNotificationTask(Context context, Intent intent, byte[] response) {
if (response.length == 0) {
return null;
}
final GenericPdu pdu =
(new PduParser(response, new MmsConfig.Overridden(new MmsConfig(context), null).
getSupportMmsContentDisposition())).parse();
if (pdu == null || !(pdu instanceof RetrieveConf)) {
android.util.Log.e(TAG, "MmsReceivedReceiver.sendNotification failed to parse pdu");
return null;
}
try {
NotificationInd ind = getNotificationInd(context, intent);
TransactionSettings transactionSettings = new TransactionSettings(context, null);
if (intent.getBooleanExtra(EXTRA_TRIGGER_PUSH, false)) {
return new NotifyRespTask(context, ind, transactionSettings);
} else {
return new AcknowledgeIndTask(context, ind, transactionSettings, (RetrieveConf) pdu);
}
} catch (MmsException e) {
Log.e(TAG, "error", e);
return null;
}
}
private static void executeNotificationTask(CommonNotificationTask task) throws IOException {
if (task == null) {
return;
}
try {
// need retry ?
task.run();
} catch (IOException e) {
Log.e(TAG, "MMS send received notification, io exception", e);
throw e;
}
}
}
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Telephony;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.logger.Log;
import java.io.File;
public class MmsSentReceiver extends BroadcastReceiver {
private static final String TAG = "MmsSentReceiver";
public static final String MMS_SENT = "com.klinker.android.messaging.MMS_SENT";
public static final String EXTRA_CONTENT_URI = "content_uri";
public static final String EXTRA_FILE_PATH = "file_path";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "MMS has finished sending, marking it as so in the database");
Uri uri = Uri.parse(intent.getStringExtra(EXTRA_CONTENT_URI));
Log.v(TAG, uri.toString());
ContentValues values = new ContentValues(1);
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT);
SqliteWrapper.update(context, context.getContentResolver(), uri, values,
null, null);
String filePath = intent.getStringExtra(EXTRA_FILE_PATH);
Log.v(TAG, filePath);
new File(filePath).delete();
}
}
@@ -0,0 +1,114 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.telephony.SmsManager;
import com.klinker.android.logger.Log;
public class SentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("sent_receiver", "marking message as sent");
Uri uri;
try {
uri = Uri.parse(intent.getStringExtra("message_uri"));
if (uri.equals("")) {
uri = null;
}
} catch (Exception e) {
uri = null;
}
switch (getResultCode()) {
case Activity.RESULT_OK:
if (uri != null) {
try {
Log.v("sent_receiver", "using supplied uri");
ContentValues values = new ContentValues();
values.put("type", 2);
values.put("read", 1);
context.getContentResolver().update(uri, values, null, null);
} catch (NullPointerException e) {
markFirstAsSent(context);
}
} else {
markFirstAsSent(context);
}
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
case SmsManager.RESULT_ERROR_NO_SERVICE:
case SmsManager.RESULT_ERROR_NULL_PDU:
case SmsManager.RESULT_ERROR_RADIO_OFF:
if (uri != null) {
Log.v("sent_receiver", "using supplied uri");
ContentValues values = new ContentValues();
values.put("type", 5);
values.put("read", true);
values.put("error_code", getResultCode());
context.getContentResolver().update(uri, values, null, null);
} else {
Log.v("sent_receiver", "using first message");
Cursor query = context.getContentResolver().query(Uri.parse("content://sms/outbox"), null, null, null, null);
// mark message failed
if (query != null && query.moveToFirst()) {
String id = query.getString(query.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("type", 5);
values.put("read", 1);
values.put("error_code", getResultCode());
context.getContentResolver().update(Uri.parse("content://sms/outbox"), values, "_id=" + id, null);
query.close();
}
}
BroadcastUtils.sendExplicitBroadcast(
context, new Intent(), Transaction.NOTIFY_SMS_FAILURE);
break;
}
BroadcastUtils.sendExplicitBroadcast(context, new Intent(), Transaction.REFRESH);
}
private void markFirstAsSent(Context context) {
Log.v("sent_receiver", "using first message");
Cursor query = context.getContentResolver().query(Uri.parse("content://sms/outbox"), null, null, null, null);
// mark message as sent successfully
if (query != null && query.moveToFirst()) {
String id = query.getString(query.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("type", 2);
values.put("read", 1);
context.getContentResolver().update(Uri.parse("content://sms/outbox"), values, "_id=" + id, null);
query.close();
}
}
}
@@ -0,0 +1,404 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.net.wifi.WifiInfo;
import android.os.Build;
import com.klinker.android.logger.Log;
/**
* Class to house all of the settings that can be used to send a message
*
* @author Jake Klinker
*/
public class Settings {
public static final int DEFAULT_SUBSCRIPTION_ID = -1;
// MMS options
private String mmsc;
private String proxy;
private String port;
private String userAgent;
private String uaProfUrl;
private String uaProfTagName;
private boolean group;
private boolean useSystemSending;
// SMS options
private boolean deliveryReports;
private boolean split;
private boolean splitCounter;
private boolean stripUnicode;
private String signature;
private String preText;
private boolean sendLongAsMms;
private int sendLongAsMmsAfter;
// SIM options
private int subscriptionId = DEFAULT_SUBSCRIPTION_ID;
/**
* Default constructor to set everything to default values
*/
public Settings() {
this("", "", "0", true, false, false, false, false, "", "", true, 3, true, DEFAULT_SUBSCRIPTION_ID);
}
/**
* Copy constuctor
* @param s is the Settings object to copy from
*/
public Settings(Settings s) {
this.mmsc = s.getMmsc();
this.proxy = s.getProxy();
this.port = s.getPort();
this.userAgent = s.getAgent();
this.uaProfUrl = s.getUserProfileUrl();
this.uaProfTagName = s.getUaProfTagName();
this.group = s.getGroup();
this.deliveryReports = s.getDeliveryReports();
this.split = s.getSplit();
this.splitCounter = s.getSplitCounter();
this.stripUnicode = s.getStripUnicode();
this.signature = s.getSignature();
this.preText = s.getPreText();
this.sendLongAsMms = s.getSendLongAsMms();
this.sendLongAsMmsAfter = s.getSendLongAsMmsAfter();
this.subscriptionId = s.getSubscriptionId();
}
/**
* @param mmsc is the address contained by the apn to send MMS to
* @param proxy is the proxy address in the apn to send MMS through
* @param port is the port from the apn to send MMS through
* @param group is a boolean specifying whether or not to send messages with multiple recipients as a group MMS message
* @param deliveryReports is a boolean to retrieve delivery reports from SMS messages
* @param split is a boolean to manually split messages (shouldn't be necessary, but some carriers do not split on their own)
* @param splitCounter adds a split counter to the front of all split messages
* @param stripUnicode replaces many unicode characters with their gsm compatible equivalent to allow for sending 160 characters instead of 70
* @param signature a signature to attach at the end of each message
* @param sendLongAsMms if a message is too long to be multiple SMS, convert it to a single MMS
* @param sendLongAsMmsAfter is an int of how many pages long an SMS must be before it is split
* @param subscriptionId is the ID for the SIM card. Can be null unless you are trying to use dual SIM support
*/
public Settings(String mmsc, String proxy, String port, boolean group,
boolean deliveryReports, boolean split, boolean splitCounter,
boolean stripUnicode, String signature, String preText, boolean sendLongAsMms,
int sendLongAsMmsAfter, boolean useSystemSending, Integer subscriptionId) {
this.mmsc = mmsc;
this.proxy = proxy;
this.port = port;
this.userAgent = "";
this.uaProfUrl = "";
this.uaProfTagName = "";
this.group = group;
this.deliveryReports = deliveryReports;
this.split = split;
this.splitCounter = splitCounter;
this.stripUnicode = stripUnicode;
this.signature = signature;
this.preText = preText;
this.sendLongAsMms = sendLongAsMms;
this.sendLongAsMmsAfter = sendLongAsMmsAfter;
setUseSystemSending(useSystemSending);
this.subscriptionId = subscriptionId != null ? subscriptionId : DEFAULT_SUBSCRIPTION_ID;
}
/**
* Sets MMSC
*
* @param mmsc is the mmsc from the apns
*/
public void setMmsc(String mmsc) {
this.mmsc = mmsc;
}
/**
* Sets the MMS Proxy
*
* @param proxy is the proxy from the apns
*/
public void setProxy(String proxy) {
this.proxy = proxy;
}
/**
* Sets the Port
*
* @param port is the port from the apns
*/
public void setPort(String port) {
this.port = port;
}
/**
* Sets the user agent
*
* @param agent is the agent to send http request with
*/
public void setAgent(String agent) { this.userAgent = agent; }
/**
* Sets the user agent profile url
*
* @param userProfileUrl is the user agent profile url
*/
public void setUserProfileUrl(String userProfileUrl) { this.uaProfUrl = userProfileUrl; }
/**
* Sets the user agent profile tag name
*
* @param tagName the tag name to use
*/
public void setUaProfTagName(String tagName) { this.uaProfTagName = tagName; }
/**
* Sets group MMS messages
*
* @param group is a boolean specifying whether or not to send messages with multiple recipients as a group MMS message
*/
public void setGroup(boolean group) {
this.group = group;
}
/**
* Sets whether to receive delivery reports from SMS messages
*
* @param deliveryReports is a boolean to retrieve delivery reports from SMS messages
*/
public void setDeliveryReports(boolean deliveryReports) {
this.deliveryReports = deliveryReports;
}
/**
* Sets whether to manually split an SMS or not
*
* @param split is a boolean to manually split messages (shouldn't be necessary, but some carriers do not split on their own)
*/
public void setSplit(boolean split) {
this.split = split;
}
/**
* Adds a split counter to the front of each split SMS
*
* @param splitCounter adds a split counter to the front of all split messages
*/
public void setSplitCounter(boolean splitCounter) {
this.splitCounter = splitCounter;
}
/**
* Sets whether or not unicode characters should be sent or converted to their GSM compatible alternative
*
* @param stripUnicode replaces many unicode characters with their gsm compatible equivalent to allow for sending 160 characters instead of 70
*/
public void setStripUnicode(boolean stripUnicode) {
this.stripUnicode = stripUnicode;
}
/**
* Sets a signature to be attached to each message
*
* @param signature a signature to attach at the end of each message
*/
public void setSignature(String signature) {
this.signature = signature;
}
/**
* Sets the text to be sent before an SMS message
*
* @param preText text to be attached to the beginning of each message
*/
public void setPreText(String preText) {
this.preText = preText;
}
/**
* Sets whether long SMS or Voice messages should instead be sent by a single MMS
*
* @param sendLongAsMms if a message is too long to be multiple SMS, convert it to a single MMS
*/
public void setSendLongAsMms(boolean sendLongAsMms) {
this.sendLongAsMms = sendLongAsMms;
}
/**
* Sets when we should convert SMS or Voice into an MMS message
*
* @param sendLongAsMmsAfter is an int of how many pages long an SMS must be before it is split
*/
public void setSendLongAsMmsAfter(int sendLongAsMmsAfter) {
this.sendLongAsMmsAfter = sendLongAsMmsAfter;
}
/**
* @param useSystemSending whether or not to use the system sending method on Lollipop+ devices
*/
public void setUseSystemSending(boolean useSystemSending) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.useSystemSending = useSystemSending;
} else {
this.useSystemSending = false;
Log.e("Settings", "System sending only available on Lollipop+ devices");
}
}
/**
* Set the subscription ID that should be used for sending. It isn't applied to receiving at this time.
*
* @param subscriptionId null if you do not want to use one.
*/
public void setSubscriptionId(Integer subscriptionId) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1 || subscriptionId == null) {
// we won't allow you to go away from the default if your device doesn't support it
this.subscriptionId = DEFAULT_SUBSCRIPTION_ID;
} else {
this.subscriptionId = subscriptionId;
}
}
/**
* @return MMSC to send through
*/
public String getMmsc() {
return this.mmsc;
}
/**
* @return the proxy to send MMS through
*/
public String getProxy() {
return this.proxy;
}
/**
* @return the port to send MMS through
*/
public String getPort() {
return this.port;
}
/**
* @return the user agent to send mms with
*/
public String getAgent() { return this.userAgent; }
/**
* @return the user agent profile url to send mms with
*/
public String getUserProfileUrl() { return this.uaProfUrl; }
/**
* @return the user agent profile tag name
*/
public String getUaProfTagName() { return this.uaProfTagName; }
/**
* @return whether or not to send Group MMS or multiple SMS/Voice messages
*/
public boolean getGroup() {
return this.group;
}
/**
* @return whether or not to request delivery reports on SMS messages
*/
public boolean getDeliveryReports() {
return this.deliveryReports;
}
/**
* @return whether or not SMS should be split manually
*/
public boolean getSplit() {
return this.split;
}
/**
* @return whether or not a split counter should be attached to manually split messages
*/
public boolean getSplitCounter() {
return this.splitCounter;
}
/**
* @return whether or not unicode chars should be substituted with gms characters
*/
public boolean getStripUnicode() {
return this.stripUnicode;
}
/**
* @return the signature attached to SMS messages
*/
public String getSignature() {
return this.signature;
}
/**
* @return the text attached to the beginning of each SMS
*/
public String getPreText() {
return this.preText;
}
/**
* @return whether or not to send long SMS or Voice as single MMS
*/
public boolean getSendLongAsMms() {
return this.sendLongAsMms;
}
/**
* @return number of pages sms must be to send instead as MMS
*/
public int getSendLongAsMmsAfter() {
return this.sendLongAsMmsAfter;
}
/**
* @return whether or not to use the system sending method on Lollipop+ devices
*/
public boolean getUseSystemSending() {
return useSystemSending;
}
/**
* @return the subscription ID or the default if one isn't set.
*/
public int getSubscriptionId() {
return subscriptionId;
}
/**
* Enables or disables logging for debug purposes logs will be written both to your devices
* logcat log and an external file you can specify so that other users can assist with debugging easily
* if you would like
*
* @param debugLogging true to enable debug logging when sending and receiving messages
* @param path the external path on the sd card to write the log to
*/
public static void setDebugLogging(boolean debugLogging, String path) {
Log.setDebug(debugLogging);
Log.setPath(path);
}
}
@@ -0,0 +1,32 @@
package com.klinker.android.send_message;
import android.os.Build;
import android.telephony.SmsManager;
public class SmsManagerFactory {
public static SmsManager createSmsManager(Settings settings) {
return createSmsManager(settings.getSubscriptionId());
}
public static SmsManager createSmsManager(int subscriptionId) {
if (subscriptionId != Settings.DEFAULT_SUBSCRIPTION_ID &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
SmsManager manager = null;
try {
manager = SmsManager.getSmsManagerForSubscriptionId(subscriptionId);
} catch (Exception e) {
e.printStackTrace();
}
if (manager != null) {
return manager;
} else {
return SmsManager.getDefault();
}
} else {
return SmsManager.getDefault();
}
}
}
@@ -0,0 +1,48 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.telephony.SmsMessage;
public class StripAccents {
public static String characters = "\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD" +
"\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03AC\u03AD" +
"\u03AE\u03AF\u03CC\u03CD\u03CE\u03CA\u03CB\u0390\u03B0\u0391\u0392\u0395\u0396\u0397\u0399" +
"\u039A\u039C\u039D\u039F\u03A1\u03A4\u03A5\u03A7\u0386\u0388\u0389\u038A\u038C\u038F\u03AA" +
"\u03AB\u0170\u0171\u0150\u0151\u0105\u0107\u0119\u0142\u0144\u015B\u017A\u017C\u0104\u0106" +
"\u0118\u0141\u0143\u015A\u0179\u017B\u00C0\u00C2\u00C3\u00C8\u00CA\u00CC\u00CE\u00D2\u00D5" +
"\u00D9\u00DB\u00E2\u00E3\u00EA\u00EE\u00F5\u00FA\u00FB\u00E7\u011B\u0161\u010D\u0159\u017E\u010F" +
"\u0165\u0148\u00E1\u00ED\u00E9\u00F3\u00FD\u016F\u011A\u0160\u010C\u0158\u017D\u010E\u0164\u0147" +
"\u00C1\u00C9\u00CD\u00D3\u00DD\u00DA\u016E\u0155\u013A\u013E\u00F4\u0154\u0139\u013D\u00D4\u00CF\u00EF\u00EB\u00CB";
public static String gsm = "AB\u0393\u0394EZH\u0398IK\u039BMN\u039EO\u03A0P\u03A3\u03A3TY\u03A6X\u03A8\u03A9AEHIOY" +
"\u03A9IYIYABEZHIKMNOPTYXAEHIO\u03A9IY\u00DC\u00FC\u00D6\u00F6acelnszzACELNSZZAAAEEIIOOUU" +
"aaeiouucescrzdtnaieoyuESCRZDTNAEIOYUUrlloRLLOIIee";
public static String stripAccents(String s) {
int[] messageData = SmsMessage.calculateLength(s, false);
if (messageData[0] != 1) {
for (int i = 0; i < characters.length(); i++) {
s = s.replaceAll(characters.substring(i, i + 1), gsm.substring(i, i + 1));
}
}
return s;
}
}
@@ -0,0 +1,925 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.send_message;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.*;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import com.android.mms.MmsConfig;
import com.android.mms.service_alt.MmsNetworkManager;
import com.android.mms.service_alt.MmsRequestManager;
import com.android.mms.service_alt.SendRequest;
import com.klinker.android.logger.Log;
import android.widget.Toast;
import com.android.mms.dom.smil.parser.SmilXmlSerializer;
import com.android.mms.transaction.MmsMessageSender;
import com.android.mms.transaction.ProgressCallbackEntity;
import com.android.mms.util.DownloadManager;
import com.android.mms.util.RateController;
import com.google.android.mms.*;
import com.google.android.mms.pdu_alt.*;
import com.google.android.mms.smil.SmilHelper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
* Class to process transaction requests for sending
*
* @author Jake Klinker
*/
public class Transaction {
private static final String TAG = "Transaction";
public static Settings settings;
private Context context;
private Intent explicitSentSmsReceiver;
private Intent explicitSentMmsReceiver;
private Intent explicitDeliveredSmsReceiver;
private boolean saveMessage = true;
public String SMS_SENT = ".SMS_SENT";
public String SMS_DELIVERED = ".SMS_DELIVERED";
public static String NOTIFY_SMS_FAILURE = ".NOTIFY_SMS_FAILURE";
public static final String MMS_ERROR = "com.klinker.android.send_message.MMS_ERROR";
public static final String REFRESH = "com.klinker.android.send_message.REFRESH";
public static final String MMS_PROGRESS = "com.klinker.android.send_message.MMS_PROGRESS";
public static final String NOTIFY_OF_DELIVERY = "com.klinker.android.send_message.NOTIFY_DELIVERY";
public static final String NOTIFY_OF_MMS = "com.klinker.android.messaging.NEW_MMS_DOWNLOADED";
public static final long NO_THREAD_ID = 0;
/**
* Sets context and initializes settings to default values
*
* @param context is the context of the activity or service
*/
public Transaction(Context context) {
this(context, new Settings());
}
/**
* Sets context and settings
*
* @param context is the context of the activity or service
* @param settings is the settings object to process send requests through
*/
public Transaction(Context context, Settings settings) {
this.settings = settings;
this.context = context;
SMS_SENT = context.getPackageName() + SMS_SENT;
SMS_DELIVERED = context.getPackageName() + SMS_DELIVERED;
if (NOTIFY_SMS_FAILURE.equals(".NOTIFY_SMS_FAILURE")) {
NOTIFY_SMS_FAILURE = context.getPackageName() + NOTIFY_SMS_FAILURE;
}
}
/**
* Called to send a new message depending on settings and provided Message object
* If you want to send message as mms, call this from the UI thread
*
* @param message is the message that you want to send
* @param threadId is the thread id of who to send the message to (can also be set to Transaction.NO_THREAD_ID)
*/
public void sendNewMessage(Message message, long threadId) {
this.saveMessage = message.getSave();
// if message:
// 1) Has images attached
// or
// 1) is enabled to send long messages as mms
// 2) number of pages for that sms exceeds value stored in settings for when to send the mms by
// 3) prefer voice is disabled
// or
// 1) more than one address is attached
// 2) group messaging is enabled
//
// then, send as MMS, else send as Voice or SMS
if (checkMMS(message)) {
try { Looper.prepare(); } catch (Exception e) { }
RateController.init(context);
DownloadManager.init(context);
sendMmsMessage(message.getText(), message.getAddresses(), message.getImages(), message.getImageNames(), message.getParts(), message.getSubject());
} else {
sendSmsMessage(message.getText(), message.getAddresses(), threadId, message.getDelay());
}
}
/**
* Optional: define a {@link BroadcastReceiver} that will get started when Android notifies us that the SMS has
* been marked as "sent". If you do not define a receiver here, it will look for the .SMS_SENT receiver
* that was defined in the AndroidManifest, as discussed in the README.md.
*
* @param intent the receiver that you want to start when the message gets marked as sent.
*/
public Transaction setExplicitBroadcastForSentSms(Intent intent) {
explicitSentSmsReceiver = intent;
return this;
}
/**
* Optional: define a {@link BroadcastReceiver} that will get started when Android notifies us that the MMS has
* been marked as "sent". If you do not define a receiver here, it will look for the .MMS_SENT receiver
* that was defined in the AndroidManifest, as discussed in the README.md.
*
* @param intent the receiver that you want to start when the message gets marked as sent.
*/
public Transaction setExplicitBroadcastForSentMms(Intent intent) {
explicitSentMmsReceiver = intent;
return this;
}
/**
* Optional: define a {@link BroadcastReceiver} that will get started when Android notifies us that the SMS has
* been marked as "delivered". If you do not define a receiver here, it will look for the .SMS_DELIVERED
* receiver that was defined in the AndroidManifest, as discussed in the README.md.
* <p/>
* Providing a receiver here does not guarantee that it will ever get started. If the {@link Settings}
* object does not have delivery reports turned on, this receiver will never get called.
*
* @param intent the receiver that you want to start when the message gets marked as sent.
*/
public Transaction setExplicitBroadcastForDeliveredSms(Intent intent) {
explicitDeliveredSmsReceiver = intent;
return this;
}
private void sendSmsMessage(String text, String[] addresses, long threadId, int delay) {
Log.v("send_transaction", "message text: " + text);
Uri messageUri = null;
int messageId = 0;
if (saveMessage) {
Log.v("send_transaction", "saving message");
// add signature to original text to be saved in database (does not strip unicode for saving though)
if (!settings.getSignature().equals("")) {
text += "\n" + settings.getSignature();
}
// save the message for each of the addresses
for (int i = 0; i < addresses.length; i++) {
Calendar cal = Calendar.getInstance();
ContentValues values = new ContentValues();
values.put("address", addresses[i]);
values.put("body", settings.getStripUnicode() ? StripAccents.stripAccents(text) : text);
values.put("date", cal.getTimeInMillis() + "");
values.put("read", 1);
values.put("type", 4);
// attempt to create correct thread id if one is not supplied
if (threadId == NO_THREAD_ID || addresses.length > 1) {
threadId = Utils.getOrCreateThreadId(context, addresses[i]);
}
Log.v("send_transaction", "saving message with thread id: " + threadId);
values.put("thread_id", threadId);
messageUri = context.getContentResolver().insert(Uri.parse("content://sms/"), values);
Log.v("send_transaction", "inserted to uri: " + messageUri);
Cursor query = context.getContentResolver().query(messageUri, new String[] {"_id"}, null, null, null);
if (query != null && query.moveToFirst()) {
messageId = query.getInt(0);
query.close();
}
Log.v("send_transaction", "message id: " + messageId);
// set up sent and delivered pending intents to be used with message request
Intent sentIntent;
if (explicitSentSmsReceiver == null) {
sentIntent = new Intent(SMS_SENT);
BroadcastUtils.addClassName(context, sentIntent, SMS_SENT);
} else {
sentIntent = explicitSentSmsReceiver;
}
sentIntent.putExtra("message_uri", messageUri == null ? "" : messageUri.toString());
PendingIntent sentPI = PendingIntent.getBroadcast(
context, messageId, sentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent deliveredIntent;
if (explicitDeliveredSmsReceiver == null) {
deliveredIntent = new Intent(SMS_DELIVERED);
BroadcastUtils.addClassName(context, deliveredIntent, SMS_DELIVERED);
} else {
deliveredIntent = explicitDeliveredSmsReceiver;
}
deliveredIntent.putExtra("message_uri", messageUri == null ? "" : messageUri.toString());
PendingIntent deliveredPI = PendingIntent.getBroadcast(
context, messageId, deliveredIntent, PendingIntent.FLAG_UPDATE_CURRENT);
ArrayList<PendingIntent> sPI = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> dPI = new ArrayList<PendingIntent>();
String body = text;
// edit the body of the text if unicode needs to be stripped
if (settings.getStripUnicode()) {
body = StripAccents.stripAccents(body);
}
if (!settings.getPreText().equals("")) {
body = settings.getPreText() + " " + body;
}
SmsManager smsManager = SmsManagerFactory.createSmsManager(settings);
Log.v("send_transaction", "found sms manager");
if (settings.getSplit()) {
Log.v("send_transaction", "splitting message");
// figure out the length of supported message
int[] splitData = SmsMessage.calculateLength(body, false);
// we take the current length + the remaining length to get the total number of characters
// that message set can support, and then divide by the number of message that will require
// to get the length supported by a single message
int length = (body.length() + splitData[2]) / splitData[0];
Log.v("send_transaction", "length: " + length);
boolean counter = false;
if (settings.getSplitCounter() && body.length() > length) {
counter = true;
length -= 6;
}
// get the split messages
String[] textToSend = splitByLength(body, length, counter);
// send each message part to each recipient attached to message
for (int j = 0; j < textToSend.length; j++) {
ArrayList<String> parts = smsManager.divideMessage(textToSend[j]);
for (int k = 0; k < parts.size(); k++) {
sPI.add(saveMessage ? sentPI : null);
dPI.add(settings.getDeliveryReports() && saveMessage ? deliveredPI : null);
}
Log.v("send_transaction", "sending split message");
sendDelayedSms(smsManager, addresses[i], parts, sPI, dPI, delay, messageUri);
}
} else {
Log.v("send_transaction", "sending without splitting");
// send the message normally without forcing anything to be split
ArrayList<String> parts = smsManager.divideMessage(body);
for (int j = 0; j < parts.size(); j++) {
sPI.add(saveMessage ? sentPI : null);
dPI.add(settings.getDeliveryReports() && saveMessage ? deliveredPI : null);
}
if (Utils.isDefaultSmsApp(context)) {
try {
Log.v("send_transaction", "sent message");
sendDelayedSms(smsManager, addresses[i], parts, sPI, dPI, delay, messageUri);
} catch (Exception e) {
// whoops...
Log.v("send_transaction", "error sending message");
Log.e(TAG, "exception thrown", e);
try {
((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Message could not be sent", Toast.LENGTH_LONG).show();
}
});
} catch (Exception f) { }
}
} else {
// not default app, so just fire it off right away for the hell of it
smsManager.sendMultipartTextMessage(addresses[i], null, parts, sPI, dPI);
}
}
}
}
}
private void sendDelayedSms(final SmsManager smsManager, final String address,
final ArrayList<String> parts, final ArrayList<PendingIntent> sPI,
final ArrayList<PendingIntent> dPI, final int delay, final Uri messageUri) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(delay);
} catch (Exception e) { }
if (checkIfMessageExistsAfterDelay(messageUri)) {
Log.v("send_transaction", "message sent after delay");
try {
smsManager.sendMultipartTextMessage(address, null, parts, sPI, dPI);
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
}
} else {
Log.v("send_transaction", "message not sent after delay, no longer exists");
}
}
}).start();
}
private boolean checkIfMessageExistsAfterDelay(Uri messageUti) {
Cursor query = context.getContentResolver().query(messageUti, new String[] {"_id"}, null, null, null);
if (query != null && query.moveToFirst()) {
query.close();
return true;
} else {
return false;
}
}
private void sendMmsMessage(String text, String[] addresses, Bitmap[] image, String[] imageNames, List<Message.Part> parts, String subject) {
// merge the string[] of addresses into a single string so they can be inserted into the database easier
String address = "";
for (int i = 0; i < addresses.length; i++) {
address += addresses[i] + " ";
}
address = address.trim();
// create the parts to send
ArrayList<MMSPart> data = new ArrayList<MMSPart>();
for (int i = 0; i < image.length; i++) {
// turn bitmap into byte array to be stored
byte[] imageBytes = Message.bitmapToByteArray(image[i]);
MMSPart part = new MMSPart();
part.MimeType = "image/jpeg";
part.Name = (imageNames != null) ? imageNames[i] : ("image_" + System.currentTimeMillis());
part.Data = imageBytes;
data.add(part);
}
// add any extra media according to their mimeType set in the message
// eg. videos, audio, contact cards, location maybe?
if (parts != null) {
for (Message.Part p : parts) {
MMSPart part = new MMSPart();
if (p.getName() != null) {
part.Name = p.getName();
} else {
part.Name = p.getContentType().split("/")[0];
}
part.MimeType = p.getContentType();
part.Data = p.getMedia();
data.add(part);
}
}
if (text != null && !text.equals("")) {
// add text to the end of the part and send
MMSPart part = new MMSPart();
part.Name = "text";
part.MimeType = "text/plain";
part.Data = text.getBytes();
data.add(part);
}
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
MessageInfo info = null;
try {
info = getBytes(context, saveMessage, address.split(" "),
data.toArray(new MMSPart[data.size()]), subject);
MmsMessageSender sender = new MmsMessageSender(context, info.location, info.bytes.length);
sender.sendMessage(info.token);
IntentFilter filter = new IntentFilter();
filter.addAction(ProgressCallbackEntity.PROGRESS_STATUS_ACTION);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int progress = intent.getIntExtra("progress", -3);
Log.v("sending_mms_library", "progress: " + progress);
// send progress broadcast to update ui if desired...
Intent progressIntent = new Intent(MMS_PROGRESS);
progressIntent.putExtra("progress", progress);
BroadcastUtils.sendExplicitBroadcast(context, progressIntent, MMS_PROGRESS);
if (progress == ProgressCallbackEntity.PROGRESS_COMPLETE) {
BroadcastUtils.sendExplicitBroadcast(context, new Intent(), REFRESH);
try {
context.unregisterReceiver(this);
} catch (Exception e) {
// TODO fix me
// receiver is not registered force close error... hmm.
}
} else if (progress == ProgressCallbackEntity.PROGRESS_ABORT) {
// This seems to get called only after the progress has reached 100 and
// then something else goes wrong, so here we will try and send again
// and see if it works
Log.v("sending_mms_library", "sending aborted for some reason...");
}
}
};
context.registerReceiver(receiver, filter);
} catch (Throwable e) {
Log.e(TAG, "exception thrown", e);
}
} else {
Log.v(TAG, "using lollipop method for sending sms");
if (settings.getUseSystemSending()) {
Log.v(TAG, "using system method for sending");
sendMmsThroughSystem(context, subject, data, addresses, explicitSentMmsReceiver);
} else {
try {
MessageInfo info = getBytes(context, saveMessage, address.split(" "),
data.toArray(new MMSPart[data.size()]), subject);
MmsRequestManager requestManager = new MmsRequestManager(context, info.bytes);
SendRequest request = new SendRequest(requestManager, Utils.getDefaultSubscriptionId(),
info.location, null, null, null, null);
MmsNetworkManager manager = new MmsNetworkManager(context, Utils.getDefaultSubscriptionId());
request.execute(context, manager);
} catch (Exception e) {
Log.e(TAG, "error sending mms", e);
}
}
}
}
public static MessageInfo getBytes(Context context, boolean saveMessage, String[] recipients,
MMSPart[] parts, String subject)
throws MmsException {
final SendReq sendRequest = new SendReq();
// create send request addresses
for (int i = 0; i < recipients.length; i++) {
final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipients[i]);
if (phoneNumbers != null && phoneNumbers.length > 0) {
sendRequest.addTo(phoneNumbers[0]);
}
}
if (subject != null) {
sendRequest.setSubject(new EncodedStringValue(subject));
}
sendRequest.setDate(Calendar.getInstance().getTimeInMillis() / 1000L);
try {
sendRequest.setFrom(new EncodedStringValue(Utils.getMyPhoneNumber(context)));
} catch (Exception e) {
Log.e(TAG, "error getting from address", e);
}
final PduBody pduBody = new PduBody();
// assign parts to the pdu body which contains sending data
long size = 0;
if (parts != null) {
for (int i = 0; i < parts.length; i++) {
MMSPart part = parts[i];
if (part != null) {
try {
PduPart partPdu = new PduPart();
partPdu.setName(part.Name.getBytes());
partPdu.setContentType(part.MimeType.getBytes());
if (part.MimeType.startsWith("text")) {
partPdu.setCharset(CharacterSets.UTF_8);
}
// Set Content-Location.
partPdu.setContentLocation(part.Name.getBytes());
int index = part.Name.lastIndexOf(".");
String contentId = (index == -1) ? part.Name
: part.Name.substring(0, index);
partPdu.setContentId(contentId.getBytes());
partPdu.setData(part.Data);
pduBody.addPart(partPdu);
size += ((2 * part.Name.getBytes().length) + part.MimeType.getBytes().length + part.Data.length + contentId.getBytes().length);
} catch (Exception e) {
}
}
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
SmilXmlSerializer.serialize(SmilHelper.createSmilDocument(pduBody), out);
PduPart smilPart = new PduPart();
smilPart.setContentId("smil".getBytes());
smilPart.setContentLocation("smil.xml".getBytes());
smilPart.setContentType(ContentType.APP_SMIL.getBytes());
smilPart.setData(out.toByteArray());
pduBody.addPart(0, smilPart);
sendRequest.setBody(pduBody);
Log.v(TAG, "setting message size to " + size + " bytes");
sendRequest.setMessageSize(size);
// add everything else that could be set
sendRequest.setPriority(PduHeaders.PRIORITY_NORMAL);
sendRequest.setDeliveryReport(PduHeaders.VALUE_NO);
sendRequest.setExpiry(1000 * 60 * 60 * 24 * 7);
sendRequest.setMessageClass(PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes());
sendRequest.setReadReport(PduHeaders.VALUE_NO);
// create byte array which will actually be sent
final PduComposer composer = new PduComposer(context, sendRequest);
final byte[] bytesToSend;
try {
bytesToSend = composer.make();
} catch (OutOfMemoryError e) {
throw new MmsException("Out of memory!");
}
MessageInfo info = new MessageInfo();
info.bytes = bytesToSend;
if (saveMessage) {
try {
PduPersister persister = PduPersister.getPduPersister(context);
info.location = persister.persist(sendRequest, Uri.parse("content://mms/outbox"), true, settings.getGroup(), null);
} catch (Exception e) {
Log.v("sending_mms_library", "error saving mms message");
Log.e(TAG, "exception thrown", e);
// use the old way if something goes wrong with the persister
insert(context, recipients, parts, subject);
}
}
try {
Cursor query = context.getContentResolver().query(info.location, new String[] {"thread_id"}, null, null, null);
if (query != null && query.moveToFirst()) {
info.token = query.getLong(query.getColumnIndex("thread_id"));
query.close();
} else {
// just default sending token for what I had before
info.token = 4444L;
}
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
info.token = 4444L;
}
return info;
}
public static final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
public static final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private static void sendMmsThroughSystem(Context context, String subject, List<MMSPart> parts,
String[] addresses, Intent explicitSentMmsReceiver) {
try {
final String fileName = "send." + String.valueOf(Math.abs(new Random().nextLong())) + ".dat";
File mSendFile = new File(context.getCacheDir(), fileName);
SendReq sendReq = buildPdu(context, addresses, subject, parts);
PduPersister persister = PduPersister.getPduPersister(context);
Uri messageUri = persister.persist(sendReq, Uri.parse("content://mms/outbox"),
true, settings.getGroup(), null);
Intent intent;
if (explicitSentMmsReceiver == null) {
intent = new Intent(MmsSentReceiver.MMS_SENT);
BroadcastUtils.addClassName(context, intent, MmsSentReceiver.MMS_SENT);
} else {
intent = explicitSentMmsReceiver;
}
intent.putExtra(MmsSentReceiver.EXTRA_CONTENT_URI, messageUri.toString());
intent.putExtra(MmsSentReceiver.EXTRA_FILE_PATH, mSendFile.getPath());
final PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri writerUri = (new Uri.Builder())
.authority(context.getPackageName() + ".MmsFileProvider")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build();
FileOutputStream writer = null;
Uri contentUri = null;
try {
writer = new FileOutputStream(mSendFile);
writer.write(new PduComposer(context, sendReq).make());
contentUri = writerUri;
} catch (final IOException e) {
Log.e(TAG, "Error writing send file", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
Bundle configOverrides = new Bundle();
configOverrides.putBoolean(SmsManager.MMS_CONFIG_GROUP_MMS_ENABLED, settings.getGroup());
String httpParams = MmsConfig.getHttpParams();
if (!TextUtils.isEmpty(httpParams)) {
configOverrides.putString(SmsManager.MMS_CONFIG_HTTP_PARAMS, httpParams);
}
configOverrides.putInt(SmsManager.MMS_CONFIG_MAX_MESSAGE_SIZE, MmsConfig.getMaxMessageSize());
if (contentUri != null) {
SmsManagerFactory.createSmsManager(settings).sendMultimediaMessage(context,
contentUri, null, configOverrides, pendingIntent);
} else {
Log.e(TAG, "Error writing sending Mms");
try {
pendingIntent.send(SmsManager.MMS_ERROR_IO_ERROR);
} catch (PendingIntent.CanceledException ex) {
Log.e(TAG, "Mms pending intent cancelled?", ex);
}
}
} catch (Exception e) {
Log.e(TAG, "error using system sending method", e);
}
}
private static SendReq buildPdu(Context context, String[] recipients, String subject,
List<MMSPart> parts) {
final SendReq req = new SendReq();
// From, per spec
final String lineNumber = Utils.getMyPhoneNumber(context);
if (!TextUtils.isEmpty(lineNumber)) {
req.setFrom(new EncodedStringValue(lineNumber));
}
// To
for (String recipient : recipients) {
req.addTo(new EncodedStringValue(recipient));
}
// Subject
if (!TextUtils.isEmpty(subject)) {
req.setSubject(new EncodedStringValue(subject));
}
// Date
req.setDate(System.currentTimeMillis() / 1000);
// Body
PduBody body = new PduBody();
// Add text part. Always add a smil part for compatibility, without it there
// may be issues on some carriers/client apps
int size = 0;
for (int i = 0; i < parts.size(); i++) {
MMSPart part = parts.get(i);
size += addTextPart(body, part, i);
}
// add a SMIL document for compatibility
ByteArrayOutputStream out = new ByteArrayOutputStream();
SmilXmlSerializer.serialize(SmilHelper.createSmilDocument(body), out);
PduPart smilPart = new PduPart();
smilPart.setContentId("smil".getBytes());
smilPart.setContentLocation("smil.xml".getBytes());
smilPart.setContentType(ContentType.APP_SMIL.getBytes());
smilPart.setData(out.toByteArray());
body.addPart(0, smilPart);
req.setBody(body);
// Message size
req.setMessageSize(size);
// Message class
req.setMessageClass(PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes());
// Expiry
req.setExpiry(DEFAULT_EXPIRY_TIME);
try {
// Priority
req.setPriority(DEFAULT_PRIORITY);
// Delivery report
req.setDeliveryReport(PduHeaders.VALUE_NO);
// Read report
req.setReadReport(PduHeaders.VALUE_NO);
} catch (InvalidHeaderValueException e) {}
return req;
}
private static int addTextPart(PduBody pb, MMSPart p, int id) {
String filename = p.Name;
final PduPart part = new PduPart();
// Set Charset if it's a text media.
if (p.MimeType.startsWith("text")) {
part.setCharset(CharacterSets.UTF_8);
}
// Set Content-Type.
part.setContentType(p.MimeType.getBytes());
// Set Content-Location.
part.setContentLocation(filename.getBytes());
int index = filename.lastIndexOf(".");
String contentId = (index == -1) ? filename
: filename.substring(0, index);
part.setContentId(contentId.getBytes());
part.setData(p.Data);
pb.addPart(part);
return part.getData().length;
}
public static class MessageInfo {
public long token;
public Uri location;
public byte[] bytes;
}
// splits text and adds split counter when applicable
private String[] splitByLength(String s, int chunkSize, boolean counter) {
int arraySize = (int) Math.ceil((double) s.length() / chunkSize);
String[] returnArray = new String[arraySize];
int index = 0;
for (int i = 0; i < s.length(); i = i + chunkSize) {
if (s.length() - i < chunkSize) {
returnArray[index++] = s.substring(i);
} else {
returnArray[index++] = s.substring(i, i + chunkSize);
}
}
if (counter && returnArray.length > 1) {
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = "(" + (i + 1) + "/" + returnArray.length + ") " + returnArray[i];
}
}
return returnArray;
}
private static Uri insert(Context context, String[] to, MMSPart[] parts, String subject) {
try {
Uri destUri = Uri.parse("content://mms");
Set<String> recipients = new HashSet<String>();
recipients.addAll(Arrays.asList(to));
long thread_id = Utils.getOrCreateThreadId(context, recipients);
// Create a dummy sms
ContentValues dummyValues = new ContentValues();
dummyValues.put("thread_id", thread_id);
dummyValues.put("body", " ");
Uri dummySms = context.getContentResolver().insert(Uri.parse("content://sms/sent"), dummyValues);
// Create a new message entry
long now = System.currentTimeMillis();
ContentValues mmsValues = new ContentValues();
mmsValues.put("thread_id", thread_id);
mmsValues.put("date", now / 1000L);
mmsValues.put("msg_box", 4);
//mmsValues.put("m_id", System.currentTimeMillis());
mmsValues.put("read", true);
mmsValues.put("sub", subject != null ? subject : "");
mmsValues.put("sub_cs", 106);
mmsValues.put("ct_t", "application/vnd.wap.multipart.related");
long imageBytes = 0;
for (MMSPart part : parts) {
imageBytes += part.Data.length;
}
mmsValues.put("exp", imageBytes);
mmsValues.put("m_cls", "personal");
mmsValues.put("m_type", 128); // 132 (RETRIEVE CONF) 130 (NOTIF IND) 128 (SEND REQ)
mmsValues.put("v", 19);
mmsValues.put("pri", 129);
mmsValues.put("tr_id", "T" + Long.toHexString(now));
mmsValues.put("resp_st", 128);
// Insert message
Uri res = context.getContentResolver().insert(destUri, mmsValues);
String messageId = res.getLastPathSegment().trim();
// Create part
for (MMSPart part : parts) {
if (part.MimeType.startsWith("image")) {
createPartImage(context, messageId, part.Data, part.MimeType);
} else if (part.MimeType.startsWith("text")) {
createPartText(context, messageId, new String(part.Data, "UTF-8"));
}
}
// Create addresses
for (String addr : to) {
createAddr(context, messageId, addr);
}
//res = Uri.parse(destUri + "/" + messageId);
// Delete dummy sms
context.getContentResolver().delete(dummySms, null, null);
return res;
} catch (Exception e) {
Log.v("sending_mms_library", "still an error saving... :(");
Log.e(TAG, "exception thrown", e);
}
return null;
}
// create the image part to be stored in database
private static Uri createPartImage(Context context, String id, byte[] imageBytes, String mimeType) throws Exception {
ContentValues mmsPartValue = new ContentValues();
mmsPartValue.put("mid", id);
mmsPartValue.put("ct", mimeType);
mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">");
Uri partUri = Uri.parse("content://mms/" + id + "/part");
Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
// Add data to part
OutputStream os = context.getContentResolver().openOutputStream(res);
ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
byte[] buffer = new byte[256];
for (int len = 0; (len = is.read(buffer)) != -1; ) {
os.write(buffer, 0, len);
}
os.close();
is.close();
return res;
}
// create the text part to be stored in database
private static Uri createPartText(Context context, String id, String text) throws Exception {
ContentValues mmsPartValue = new ContentValues();
mmsPartValue.put("mid", id);
mmsPartValue.put("ct", "text/plain");
mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">");
mmsPartValue.put("text", text);
Uri partUri = Uri.parse("content://mms/" + id + "/part");
Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
return res;
}
// add address to the request
private static Uri createAddr(Context context, String id, String addr) throws Exception {
ContentValues addrValues = new ContentValues();
addrValues.put("address", addr);
addrValues.put("charset", "106");
addrValues.put("type", 151); // TO
Uri addrUri = Uri.parse("content://mms/" + id + "/addr");
Uri res = context.getContentResolver().insert(addrUri, addrValues);
return res;
}
/**
* A method for checking whether or not a certain message will be sent as mms depending on its contents and the settings
*
* @param message is the message that you are checking against
* @return true if the message will be mms, otherwise false
*/
public boolean checkMMS(Message message) {
return message.getImages().length != 0 ||
(message.getParts().size() != 0) ||
(settings.getSendLongAsMms() && Utils.getNumPages(settings, message.getText()) > settings.getSendLongAsMmsAfter()) ||
(message.getAddresses().length > 1 && settings.getGroup()) ||
message.getSubject() != null;
}
}
@@ -0,0 +1,434 @@
package com.klinker.android.send_message;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.mms.service_alt.MmsNetworkManager;
import com.android.mms.service_alt.exception.MmsNetworkException;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.logger.Log;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Common methods to be used for data connectivity/sending messages ect
*
* @author Jake Klinker
*/
public class Utils {
/**
* characters to compare against when checking for 160 character sending compatibility
*/
public static final String GSM_CHARACTERS_REGEX = "^[A-Za-z0-9 \\r\\n@Ł$ĽčéůěňÇŘřĹĺ\u0394_\u03A6\u0393\u039B\u03A9\u03A0\u03A8\u03A3\u0398\u039EĆćßÉ!\"#$%&'()*+,\\-./:;<=>?ĄÄÖŃܧżäöńüŕ^{}\\\\\\[~\\]|\u20AC]*$";
private static final String TAG = "Utils";
public static final int DEFAULT_SUBSCRIPTION_ID = 1;
/**
* Gets the current users phone number
*
* @param context is the context of the activity or service
* @return a string of the phone number on the device
*/
public static String getMyPhoneNumber(Context context) {
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
public interface Task<T> {
T run() throws IOException;
}
public static <T> T ensureRouteToMmsNetwork(Context context, String url, String proxy, Task<T> task) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return ensureRouteToMmsNetworkMarshmallow(context, task);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return ensureRouteToMmsNetworkLollipop(context, task);
} else {
ensureRouteToHost(context, url, proxy);
return task.run();
}
}
@TargetApi(Build.VERSION_CODES.M)
private static <T> T ensureRouteToMmsNetworkMarshmallow(Context context, Task<T> task) throws IOException {
final MmsNetworkManager networkManager = new MmsNetworkManager(context.getApplicationContext(), Utils.getDefaultSubscriptionId());
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = null;
try {
network = networkManager.acquireNetwork();
connectivityManager.bindProcessToNetwork(network);
return task.run();
} catch (MmsNetworkException e) {
throw new IOException(e);
} finally {
if (network != null) {
connectivityManager.bindProcessToNetwork(null);
}
networkManager.releaseNetwork();
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static <T> T ensureRouteToMmsNetworkLollipop(Context context, Task<T> task) throws IOException {
final MmsNetworkManager networkManager = new MmsNetworkManager(context.getApplicationContext(), Utils.getDefaultSubscriptionId());
Network network = null;
try {
network = networkManager.acquireNetwork();
ConnectivityManager.setProcessDefaultNetwork(network);
return task.run();
} catch (MmsNetworkException e) {
throw new IOException(e);
} finally {
if (network != null) {
ConnectivityManager.setProcessDefaultNetwork(null);
}
networkManager.releaseNetwork();
}
}
/**
* Ensures that the host MMSC is reachable
*
* @param context is the context of the activity or service
* @param url is the MMSC to check
* @param proxy is the proxy of the APN to check
* @throws java.io.IOException when route cannot be established
*/
public static void ensureRouteToHost(Context context, String url, String proxy) throws IOException {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
InetAddress inetAddr;
if (proxy != null && proxy.trim().length() != 0) {
try {
inetAddr = InetAddress.getByName(proxy);
} catch (UnknownHostException e) {
throw new IOException("Cannot establish route for " + url +
": Unknown proxy " + proxy);
}
try {
Method requestRoute = ConnectivityManager.class.getMethod("requestRouteToHostAddress", Integer.TYPE, InetAddress.class);
if (!((Boolean) requestRoute.invoke(connMgr, ConnectivityManager.TYPE_MOBILE_MMS, inetAddr))) {
throw new IOException("Cannot establish route to proxy " + inetAddr);
}
} catch (Exception e) {
Log.e(TAG, "Cannot establishh route to proxy " + inetAddr, e);
}
} else {
Uri uri = Uri.parse(url);
try {
inetAddr = InetAddress.getByName(uri.getHost());
} catch (UnknownHostException e) {
throw new IOException("Cannot establish route for " + url + ": Unknown host");
}
try {
Method requestRoute = ConnectivityManager.class.getMethod("requestRouteToHostAddress", Integer.TYPE, InetAddress.class);
if (!((Boolean) requestRoute.invoke(connMgr, ConnectivityManager.TYPE_MOBILE_MMS, inetAddr))) {
throw new IOException("Cannot establish route to proxy " + inetAddr);
}
} catch (Exception e) {
Log.e(TAG, "Cannot establishh route to proxy " + inetAddr + " for " + url, e);
}
}
}
/**
* Checks whether or not mobile data is enabled and returns the result
*
* @param context is the context of the activity or service
* @return true if data is enabled or false if disabled
*/
public static Boolean isMobileDataEnabled(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class<?> c = Class.forName(cm.getClass().getName());
Method m = c.getDeclaredMethod("getMobileDataEnabled");
m.setAccessible(true);
return (Boolean) m.invoke(cm);
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
return null;
}
}
/**
* Checks mobile data enabled based on telephonymanager
*
* @param telephonyManager the telephony manager
*/
public static boolean isDataEnabled(TelephonyManager telephonyManager) {
try {
Class<?> c = telephonyManager.getClass();
Method m = c.getMethod("getDataEnabled");
return (boolean) m.invoke(telephonyManager);
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
return true;
}
}
/**
* Checks mobile data enabled based on telephonymanager and sim card
*
* @param telephonyManager the telephony manager
* @param subId the sim card id
*/
public static boolean isDataEnabled(TelephonyManager telephonyManager, int subId) {
try {
Class<?> c = telephonyManager.getClass();
Method m = c.getMethod("getDataEnabled", int.class);
return (boolean) m.invoke(telephonyManager, subId);
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
return isDataEnabled(telephonyManager);
}
}
/**
* Toggles mobile data
*
* @param context is the context of the activity or service
* @param enabled is whether to enable or disable data
*/
public static void setMobileDataEnabled(Context context, boolean enabled) {
String methodName;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
try {
ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class conmanClass = Class.forName(conman.getClass().getName());
Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
Object iConnectivityManager = iConnectivityManagerField.get(conman);
Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
}
} else {
// TODO find a better way to do this on lollipop!
// This will actually not work due to no permission for android.permission.MODIFY_PHONE_STATE, which
// is a system level permission and cannot be accessed for third party apps.
try {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object telephonyService = m.invoke(tm);
c = Class.forName(telephonyService.getClass().getName());
m = c.getDeclaredMethod("setDataEnabled", Boolean.TYPE);
m.setAccessible(true);
m.invoke(telephonyService, enabled);
} catch (Exception e) {
Log.e(TAG, "error enabling data on lollipop", e);
}
}
}
/**
* Gets the number of pages in the SMS based on settings and the length of string
*
* @param settings is the settings object to check against
* @param text is the text from the message object to be sent
* @return the number of pages required to hold message
*/
public static int getNumPages(Settings settings, String text) {
if (settings.getStripUnicode()) {
text = StripAccents.stripAccents(text);
}
int[] data = SmsMessage.calculateLength(text, false);
return data[0];
}
/**
* Gets the current thread_id or creates a new one for the given recipient
* @param context is the context of the activity or service
* @param recipient is the person message is being sent to
* @return the thread_id to use in the database
*/
public static long getOrCreateThreadId(Context context, String recipient) {
Set<String> recipients = new HashSet<String>();
recipients.add(recipient);
return getOrCreateThreadId(context, recipients);
}
/**
* Gets the current thread_id or creates a new one for the given recipient
* @param context is the context of the activity or service
* @param recipients is the set of people message is being sent to
* @return the thread_id to use in the database
*/
public static long getOrCreateThreadId(
Context context, Set<String> recipients) {
Uri.Builder uriBuilder = Uri.parse("content://mms-sms/threadID").buildUpon();
for (String recipient : recipients) {
if (isEmailAddress(recipient)) {
recipient = extractAddrSpec(recipient);
}
uriBuilder.appendQueryParameter("recipient", recipient);
}
Uri uri = uriBuilder.build();
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, new String[]{"_id"}, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
long id = cursor.getLong(0);
cursor.close();
return id;
} else {
}
} finally {
cursor.close();
}
}
Random random = new Random();
return random.nextLong();
//throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
}
public static boolean doesThreadIdExist(Context context, long threadId) {
Uri uri = Uri.parse("content://mms-sms/conversations/" + threadId + "/");
Cursor cursor = context.getContentResolver().query(uri, new String[] {"_id"}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
cursor.close();
return true;
} else {
return false;
}
}
private static boolean isEmailAddress(String address) {
if (TextUtils.isEmpty(address)) {
return false;
}
String s = extractAddrSpec(address);
Matcher match = EMAIL_ADDRESS_PATTERN.matcher(s);
return match.matches();
}
private static final Pattern EMAIL_ADDRESS_PATTERN
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
private static final Pattern NAME_ADDR_EMAIL_PATTERN =
Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*");
private static String extractAddrSpec(String address) {
Matcher match = NAME_ADDR_EMAIL_PATTERN.matcher(address);
if (match.matches()) {
return match.group(2);
}
return address;
}
/**
* Gets the default settings from a shared preferences file associated with your app
* @param context is the context of the activity or service
* @return the settings object to send with
*/
public static Settings getDefaultSendSettings(Context context) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Settings sendSettings = new Settings();
sendSettings.setMmsc(sharedPrefs.getString("mmsc_url", ""));
sendSettings.setProxy(sharedPrefs.getString("mms_proxy", ""));
sendSettings.setPort(sharedPrefs.getString("mms_port", ""));
sendSettings.setAgent(sharedPrefs.getString("mms_agent", ""));
sendSettings.setUserProfileUrl(sharedPrefs.getString("mms_user_agent_profile_url", ""));
sendSettings.setUaProfTagName(sharedPrefs.getString("mms_user_agent_tag_name", ""));
sendSettings.setGroup(sharedPrefs.getBoolean("group_message", true));
sendSettings.setDeliveryReports(sharedPrefs.getBoolean("delivery_reports", false));
sendSettings.setSplit(sharedPrefs.getBoolean("split_sms", false));
sendSettings.setSplitCounter(sharedPrefs.getBoolean("split_counter", false));
sendSettings.setStripUnicode(sharedPrefs.getBoolean("strip_unicode", false));
sendSettings.setSignature(sharedPrefs.getString("signature", ""));
sendSettings.setSendLongAsMms(true);
sendSettings.setSendLongAsMmsAfter(3);
return sendSettings;
}
/**
* Determines whether or not the user has Android 4.4 KitKat
* @return true if version code on device is >= kitkat
*/
public static boolean hasKitKat() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
}
/**
* Determines whether or not the app is the default SMS app on a device
* @param context
* @return true if app is default
*/
public static boolean isDefaultSmsApp(Context context) {
if (hasKitKat()) {
return context.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(context));
}
return true;
}
/**
* Determins whether or not the app has enabled MMS over WiFi
* @param context
* @return true if enabled
*/
public static boolean isMmsOverWifiEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("mms_over_wifi", false);
}
public static int getDefaultSubscriptionId() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
return SmsManager.getDefaultSmsSubscriptionId();
} else {
return DEFAULT_SUBSCRIPTION_ID;
}
}
}