Java Code Examples for android.telephony.SmsManager#sendMultipartTextMessage()

The following examples show how to use android.telephony.SmsManager#sendMultipartTextMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GpsSearch.java    From Finder with GNU General Public License v3.0 6 votes vote down vote up
private void start_send() {   //sending to all who asked
    if ((Build.VERSION.SDK_INT >= 23 &&
            (getApplicationContext().checkSelfPermission(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)) ||
            Build.VERSION.SDK_INT < 23) {
        //adding battery data
        IntentFilter bat_filt= new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent battery = getApplicationContext().registerReceiver(null, bat_filt);
        int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = level / (float) scale;
        String batLevel = String.valueOf(Math.round(batteryPct*100));
        sms_answer.append(" bat:");
        sms_answer.append(batLevel);
        sms_answer.append("%\n");

        SmsManager sManager = SmsManager.getDefault();
        ArrayList<String> parts = sManager.divideMessage(sms_answer.toString());
        for (String number : phones) {
            sManager.sendMultipartTextMessage(number, null, parts, null,null);
        }
    }

    stopSelf();
}
 
Example 2
Source File: SmsSenderService.java    From SmsScheduler with GNU General Public License v2.0 6 votes vote down vote up
private void sendSms(SmsModel sms) {
    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<>();
    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<>();
    PendingIntent sentPendingIntent = getPendingIntent(sms.getTimestampCreated(), SmsSentReceiver.class);
    PendingIntent deliveredPendingIntent = getPendingIntent(sms.getTimestampCreated(), SmsDeliveredReceiver.class);

    SmsManager smsManager = getSmsManager(sms.getSubscriptionId());
    ArrayList<String> smsMessage = smsManager.divideMessage(sms.getMessage());
    boolean deliveryReports = PreferenceManager
        .getDefaultSharedPreferences(getApplicationContext())
        .getBoolean(SmsSchedulerPreferenceActivity.PREFERENCE_DELIVERY_REPORTS, false)
    ;
    for (int i = 0; i < smsMessage.size(); i++) {
        sentPendingIntents.add(i, sentPendingIntent);
        if (deliveryReports) {
            deliveredPendingIntents.add(i, deliveredPendingIntent);
        }
    }
    smsManager.sendMultipartTextMessage(
        sms.getRecipientNumber(),
        null,
        smsMessage,
        sentPendingIntents,
        deliveryReports ? deliveredPendingIntents : null
    );
}
 
Example 3
Source File: SMS.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static boolean sendSMS(String destination, String message) {
    try {

        // TODO TRACK PARTS ON SEND INTENTS
        final SmsManager smsManager = SmsManager.getDefault();
        if (message.length() > 160) {
            final ArrayList<String> messageParts = smsManager.divideMessage(message);
            smsManager.sendMultipartTextMessage(destination, null, messageParts, null, null);
        } else {
            smsManager.sendTextMessage(destination, null, message, null, null);
        }
        return true;
    } catch (SecurityException e) {
        UserError.Log.wtf(TAG, "Error sending SMS! no permission? " + e);
        // warn user? disable feature?
    }
    return false;
}
 
Example 4
Source File: SMS.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static boolean sendSMS(String destination, String message) {
    try {

        // TODO TRACK PARTS ON SEND INTENTS
        final SmsManager smsManager = SmsManager.getDefault();
        if (message.length() > 160) {
            final ArrayList<String> messageParts = smsManager.divideMessage(message);
            smsManager.sendMultipartTextMessage(destination, null, messageParts, null, null);
        } else {
            smsManager.sendTextMessage(destination, null, message, null, null);
        }
        return true;
    } catch (SecurityException e) {
        UserError.Log.wtf(TAG, "Error sending SMS! no permission? " + e);
        // warn user? disable feature?
    }
    return false;
}
 
Example 5
Source File: SmsSenderService.java    From RememBirthday with GNU General Public License v3.0 6 votes vote down vote up
private void sendSms(AutoSms sms, boolean deliveryReports) {
    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<>();
    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<>();
    PendingIntent sentPendingIntent = getPendingIntent(sms.getDateCreated().getTime(), SmsSentReceiver.class);
    PendingIntent deliveredPendingIntent = getPendingIntent(sms.getDateCreated().getTime(), SmsDeliveredReceiver.class);

    SmsManager smsManager = getSmsManager(sms.getSubscriptionId());
    ArrayList<String> smsMessage = smsManager.divideMessage(sms.getMessage());
    for (int i = 0; i < smsMessage.size(); i++) {
        sentPendingIntents.add(i, sentPendingIntent);
        if (deliveryReports) {
            deliveredPendingIntents.add(i, deliveredPendingIntent);
        }
    }
    smsManager.sendMultipartTextMessage(
        sms.getRecipientPhoneNumber(),
        null,
        smsMessage,
        sentPendingIntents,
        deliveryReports ? deliveredPendingIntents : null
    );
}
 
Example 6
Source File: SmsRepositoryImpl.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Sends an SMS
 *
 * @param number The phone number the sms should be sent to.
 * @param parts  The message that should be sent.
 */
@SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops"})
private void sendSmsToOS(SendingStateReceiver stateReceiver, String number, List<String> parts) {
    SmsManager sms = SmsManager.getDefault();
    int uniqueIntentId = joinStrings(parts).hashCode();
    String uniqueKeyPrefix = uniqueIntentId + "_" + UUID.randomUUID().toString();
    ArrayList<PendingIntent> sentMessagePIs = new ArrayList<>();
    for (int i = 0; i < parts.size(); i++) {
        String smsKey = uniqueKeyPrefix + '_' + i;
        stateReceiver.addSmsKey(smsKey);
        PendingIntent sentPI = PendingIntent.getBroadcast(
                context,
                uniqueIntentId,
                new Intent(sendSmsAction).putExtra(SMS_KEY, smsKey),
                PendingIntent.FLAG_ONE_SHOT);
        sentMessagePIs.add(sentPI);
        uniqueIntentId++;
    }

    sms.sendMultipartTextMessage(number, null, new ArrayList<>(parts),
            sentMessagePIs, null);
}
 
Example 7
Source File: sendSMS.java    From ShellMS with GNU General Public License v3.0 6 votes vote down vote up
private void sendsms(final String phoneNumber, final String message, final Boolean AddtoSent)	{
try {
	String SENT = TAG + "_SMS_SENT";
	Intent myIntent = new Intent(SENT);
   	PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, myIntent, 0);
       
   	SmsManager sms = SmsManager.getDefault();
       ArrayList<String> msgparts = sms.divideMessage(message);
   	ArrayList<PendingIntent> sentPendingIntents = new ArrayList<>();
   	int msgcount = msgparts.size();

   	for (int i = 0; i < msgcount; i++) {
           sentPendingIntents.add(sentPI);
       }

   	sms.sendMultipartTextMessage(phoneNumber, null, msgparts, sentPendingIntents, null);
       if (AddtoSent)	{
		addMessageToSent(phoneNumber, message);
	}
} catch (Exception e) {
       e.printStackTrace();
       Log.e(TAG, "undefined Error: SMS sending failed ... please REPORT to ISSUE Tracker");
   }
  }
 
Example 8
Source File: Tracking.java    From Finder with GNU General Public License v3.0 5 votes vote down vote up
private void append_send_coordinates(String lat, String lon, String speed, String date) {
    //creating message
    sms_text.append(lat);
    sms_text.append(";");
    sms_text.append(lon);
    sms_text.append(";");
    sms_text.append(speed);
    sms_text.append(";");
    sms_text.append(date);
    sms_text.append("\n");
    coords_counter++;

    //buffer is full, time to send or stop service
    if (coords_counter == sms_buffer_max) {
        coords_counter = 0;
        if (sms_counter < sms_number) {
            if ((Build.VERSION.SDK_INT >= 23 &&
                    (getApplicationContext().checkSelfPermission(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)) ||
                    Build.VERSION.SDK_INT < 23) {
                SmsManager sManager = SmsManager.getDefault();
                ArrayList<String> parts = sManager.divideMessage(sms_text.toString());
                sManager.sendMultipartTextMessage(phone, null, parts, null,null);
                sms_text = new StringBuilder("");
                sms_counter++;
                builder.setContentText(getString(R.string.sms_sent, sms_counter));

                //update fields in TrackingStatus via intent
                update_intent.setAction("update_fields");
                LocalBroadcastManager.getInstance(this).sendBroadcast(update_intent);
            }
        }

        //second check to stop service straight after sending all messages
        if (sms_counter == sms_number) {
            //all SMS are sent, notification will be created in onDestroy
            stopSelf();
        }
    }
}
 
Example 9
Source File: SmsSenderService.java    From Locate-driver with GNU General Public License v3.0 5 votes vote down vote up
public void sendSMS(String phoneNumber, String message) {
    //Log.d(TAG, "Send SMS: " + phoneNumber + ", " + message);
    //on samsung intents can't be null. the messages are not sent if intents are null
    ArrayList<PendingIntent> samsungFix = new ArrayList<>();
    samsungFix.add(PendingIntent.getBroadcast(context, 0, new Intent("SMS_RECEIVED"), 0));

    SmsManager smsManager = SmsManager.getDefault();
    ArrayList<String> parts = smsManager.divideMessage(message);
    smsManager.sendMultipartTextMessage(phoneNumber, null, parts, samsungFix, samsungFix);
}
 
Example 10
Source File: MainActivity.java    From GPS2SMS with GNU General Public License v3.0 5 votes vote down vote up
public void sendSMS_Debug(String lMsg) {

        phoneToSendSMS = plainPh.getText().toString().replace("-", "")
                .replace(" ", "").replace("(", "").replace(")", "").replace(".", "");

        if (phoneToSendSMS.equalsIgnoreCase("")) {
            DBHelper.ShowToast(MainActivity.this,
                    R.string.error_no_phone_number, Toast.LENGTH_LONG);
        } else {
            try {


            // update saved number
            dbHelper = new DBHelper(MainActivity.this);
            dbHelper.setSlot(0, "", phoneToSendSMS);
            dbHelper.close();

            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> parts = smsManager.divideMessage(lMsg);
            smsManager.sendMultipartTextMessage(phoneToSendSMS, null, parts, null, null);

            DBHelper.ShowToastT(MainActivity.this, getString(R.string.info_sms_sent),
                    Toast.LENGTH_SHORT);

            } catch (Exception e) {
                DBHelper.ShowToastT(MainActivity.this, e.getMessage(),
                        Toast.LENGTH_LONG);
            }

        }

    }
 
Example 11
Source File: SMSSendHelper.java    From BlackList with Apache License 2.0 4 votes vote down vote up
public boolean sendSMS(Context context, @NonNull String phoneNumber, @NonNull String message) {
    if (phoneNumber.isEmpty() || message.isEmpty()) {
        return false;
    }

    // get application context
    context = context.getApplicationContext();

    // get flag of delivery waiting
    boolean delivery = false;
    if (Settings.getBooleanValue(context, Settings.DELIVERY_SMS_NOTIFICATION)) {
        delivery = true;
    }

    // write the sent message to the Outbox
    long messageId = writeSMSMessageToOutbox(context, phoneNumber, message);

    // divide message into parts
    SmsManager smsManager = getSmsManager(context);
    ArrayList<String> messageParts = smsManager.divideMessage(message);

    // create pending intents for each part of message
    ArrayList<PendingIntent> sentIntents = new ArrayList<>(messageParts.size());
    ArrayList<PendingIntent> deliveryIntents = new ArrayList<>(messageParts.size());
    for (int i = 0; i < messageParts.size(); i++) {
        String messagePart = messageParts.get(i);
        int messagePartId = i + 1;

        // pending intent for getting result of SMS sending
        PendingIntent pendingIntent = createPendingIntent(context, SMS_SENT, messageId,
                phoneNumber, messagePart, messagePartId, messageParts.size(), delivery);
        sentIntents.add(pendingIntent);

        if (delivery) {
            // pending intent for getting result of SMS delivery
            pendingIntent = createPendingIntent(context, SMS_DELIVERY, messageId,
                    phoneNumber, messagePart, messagePartId, messageParts.size(), true);
            deliveryIntents.add(pendingIntent);
        }
    }

    // send message
    smsManager.sendMultipartTextMessage(phoneNumber, null, messageParts, sentIntents, deliveryIntents);

    // send internal event message
    InternalEventBroadcast.sendSMSWasWritten(context, phoneNumber);

    return true;
}
 
Example 12
Source File: Sms.java    From cordova-sms-plugin with MIT License 4 votes vote down vote up
private void send(final CallbackContext callbackContext, String phoneNumber, String message) {
	SmsManager manager = SmsManager.getDefault();
	final ArrayList<String> parts = manager.divideMessage(message);

	// by creating this broadcast receiver we can check whether or not the SMS was sent
	final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		boolean anyError = false; //use to detect if one of the parts failed
		int partsCount = parts.size(); //number of parts to send

		@Override
		public void onReceive(Context context, Intent intent) {
			switch (getResultCode()) {
			case SmsManager.STATUS_ON_ICC_SENT:
			case Activity.RESULT_OK:
				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:
				anyError = true;
				break;
			}
			// trigger the callback only when all the parts have been sent
			partsCount--;
			if (partsCount == 0) {
				if (anyError) {
					callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
				} else {
					callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
				}
				cordova.getActivity().unregisterReceiver(this);
			}
		}
	};

	// randomize the intent filter action to avoid using the same receiver
	String intentFilterAction = INTENT_FILTER_SMS_SENT + java.util.UUID.randomUUID().toString();
	this.cordova.getActivity().registerReceiver(broadcastReceiver, new IntentFilter(intentFilterAction));

	PendingIntent sentIntent = PendingIntent.getBroadcast(this.cordova.getActivity(), 0, new Intent(intentFilterAction), 0);

	// depending on the number of parts we send a text message or multi parts
	if (parts.size() > 1) {
		ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
		for (int i = 0; i < parts.size(); i++) {
			sentIntents.add(sentIntent);
		}
		manager.sendMultipartTextMessage(phoneNumber, null, parts, sentIntents, null);
	}
	else {
		manager.sendTextMessage(phoneNumber, null, message, sentIntent, null);
	}
}
 
Example 13
Source File: SmsIntentService.java    From android-sms-gateway with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent)
{
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty())
    {
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))
        {
            String number = extras.getString("number");
            String message = extras.getString("message");
            if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(message))
            {
                try
                {
                    if (!number.startsWith("+"))
                    {
                        number = "+" + number;
                    }
                    SmsManager smsManager = SmsManager.getDefault();
                    ArrayList<String> parts = smsManager.divideMessage(message);
                    if (parts.size() > 1)
                    {
                        smsManager.sendMultipartTextMessage(number, null, parts, null, null);
                    }
                    else
                    {
                        smsManager.sendTextMessage(number, null, message, null, null);
                    }

                    String result = number + ": " + message;
                    Log.i(TAG, result);

                    sendNotification(result);

                    ContentValues values = new ContentValues();
                    values.put("address", number);
                    values.put("body", message);
                    getApplicationContext().getContentResolver()
                                           .insert(Uri.parse("content://sms/sent"), values);
                }
                catch (Exception ex)
                {
                    Log.e(TAG, ex.toString());
                }
            }
        }
    }
    SmsBroadcastReceiver.completeWakefulIntent(intent);
}