android.telephony.SmsManager Java Examples

The following examples show how to use android.telephony.SmsManager. 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: public_func.java    From dingtalk-sms with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
static void send_sms(Context context, String send_to, String content, int sub_id) {
    android.telephony.SmsManager sms_manager;
    String sim_card = "1";
    if (sub_id == -1) {
        sms_manager = SmsManager.getDefault();
    } else {
        sms_manager = SmsManager.getSmsManagerForSubscriptionId(sub_id);
        sim_card = "2";
    }
    ArrayList<String> divideContents = sms_manager.divideMessage(content);
    ArrayList<PendingIntent> send_receiver_list = new ArrayList<>();
    IntentFilter filter = new IntentFilter("send_sms");
    BroadcastReceiver receiver = new sms_send_receiver();
    context.getApplicationContext().registerReceiver(receiver, filter);
    Intent sent_intent = new Intent("send_sms");
    sent_intent.putExtra("sim_card", sim_card);
    sent_intent.putExtra("send_to", send_to);
    sent_intent.putExtra("content", content);
    PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, sent_intent, PendingIntent.FLAG_CANCEL_CURRENT);
    send_receiver_list.add(sentIntent);
    sms_manager.sendMultipartTextMessage(send_to, null, divideContents, send_receiver_list, null);
}
 
Example #2
Source File: OpenFitService.java    From OpenFit with MIT License 6 votes vote down vote up
public void sendRejectMessage(String messageId, String phoneNumber) {
    StringBuilder updatedString = new StringBuilder();
    for(int i = 0; i < messageId.length(); i++) {
        updatedString.append(messageId.charAt(i));
        if(messageId.charAt(i) != '0') {
            break;
        }
    }
    int messageIdInt = Integer.parseInt(updatedString.toString(), 16);
    Log.d(LOG_TAG, "Reject message ID: " + messageId + ", " + messageIdInt);
    int msgSize = oPrefs.getInt("reject_messages_size");
    if(msgSize > 0 && msgSize > messageIdInt) {
        Log.d(LOG_TAG, "Sending reject message: " + oPrefs.getString("reject_message_" + messageIdInt) + ", to: " + phoneNumber);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNumber, null, oPrefs.getString("reject_message_" + messageIdInt), null, null);
            Toast.makeText(getApplicationContext(), R.string.toast_send_sms_success, Toast.LENGTH_SHORT).show();
        }
        catch(Exception e) {
            Toast.makeText(getApplicationContext(), R.string.toast_send_sms_failed, Toast.LENGTH_SHORT).show();
            Log.d(LOG_TAG, "Sending sms failed: " + e.toString());
        }
    }
}
 
Example #3
Source File: SmsSender.java    From medic-android with GNU Affero General Public License v3.0 6 votes vote down vote up
SmsSender(EmbeddedBrowserActivity parent) {
	this.parent = parent;
	this.smsManager = SmsManager.getDefault();

	parent.registerReceiver(new BroadcastReceiver() {
		@Override public void onReceive(Context ctx, Intent intent) {
			log("BroadcastReceiver.onReceive() :: %s", intent.getAction());

			try {
				switch(intent.getAction()) {
					case SENDING_REPORT:
						new SendingReportHandler().handle(intent, getResultCode());
						break;
					case DELIVERY_REPORT:
						new DeliveryReportHandler().handle(intent);
						break;
					default:
						throw new IllegalStateException("Unexpected intent: " + intent);
				}
			} catch(Exception ex) {
				warn(ex, "BroadcastReceiver threw exception '%s' when processing intent: %s",
						ex.getClass(), ex.getMessage());
			}
		}
	}, createIntentFilter());
}
 
Example #4
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 #5
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 发送短信
 * @param phoneNumber 接收号码
 * @param content     短信内容
 * @return {@code true} success, {@code false} fail
 */
@RequiresPermission(android.Manifest.permission.SEND_SMS)
public static boolean sendSmsSilent(final String phoneNumber, final String content) {
    if (TextUtils.isEmpty(content)) return false;
    try {
        PendingIntent sentIntent = PendingIntent.getBroadcast(DevUtils.getContext(), 0, new Intent("send"), 0);
        SmsManager smsManager = SmsManager.getDefault();
        if (content.length() >= 70) {
            List<String> ms = smsManager.divideMessage(content);
            for (String str : ms) {
                smsManager.sendTextMessage(phoneNumber, null, str, sentIntent, null);
            }
        } else {
            smsManager.sendTextMessage(phoneNumber, null, content, sentIntent, null);
        }
        return true;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "sendSmsSilent");
    }
    return false;
}
 
Example #6
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 #7
Source File: DisplayMessageActivity.java    From DroidForce with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_display_message);
	
	TextView tv = (TextView) findViewById(R.id.resultInterComponent);
	
	Bundle extras = getIntent().getExtras();
	if (extras == null) {
	  return;
	}
	// get data via the key
	String destination = extras.getString("destination");
	String message = extras.getString("message");
	String imei = extras.getString("imei");
	
	tv.setText("dest: " + destination + "\nmessage: " + message + "\nimei: " + imei + "\n\nSMS sent...");
	
	SmsManager smsManager = SmsManager.getDefault();
	smsManager.sendTextMessage(destination, null, message, null, null);
}
 
Example #8
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 #9
Source File: public_func.java    From telegram-sms with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static void send_fallback_sms(Context context, String content, int sub_id) {
    final String TAG = "send_fallback_sms";
    if (androidx.core.content.PermissionChecker.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PermissionChecker.PERMISSION_GRANTED) {
        Log.d(TAG, "No permission.");
        return;
    }
    SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE);
    String trust_number = sharedPreferences.getString("trusted_phone_number", null);
    if (trust_number == null) {
        Log.i(TAG, "The trusted number is empty.");
        return;
    }
    if (!sharedPreferences.getBoolean("fallback_sms", false)) {
        Log.i(TAG, "Did not open the SMS to fall back.");
        return;
    }
    android.telephony.SmsManager sms_manager;
    if (sub_id == -1) {
        sms_manager = SmsManager.getDefault();
    } else {
        sms_manager = SmsManager.getSmsManagerForSubscriptionId(sub_id);
    }
    ArrayList<String> divideContents = sms_manager.divideMessage(content);
    sms_manager.sendMultipartTextMessage(trust_number, null, divideContents, null, null);

}
 
Example #10
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 #11
Source File: ThreadSendSMS.java    From GPS2SMS with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent arg1) {

    setSendRecFired(send_receiver_fired + 1);

    switch (getResultCode()) {
        case Activity.RESULT_OK:
            setResSend(context.getString(R.string.info_sms_sent));
            break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
            setResSend(context.getString(R.string.info_sms_generic));
            break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
            setResSend(context.getString(R.string.info_sms_noservice));
            break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
            setResSend(context.getString(R.string.info_sms_nullpdu));
            break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
            setResSend(context.getString(R.string.info_sms_radioof));
            break;
    }
}
 
Example #12
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 #13
Source File: AutoSendSMS.java    From AndroidTranslucentUI with Apache License 2.0 6 votes vote down vote up
/**
 * �Զ�������֤��
 * @author KEEN
 * @lastChangeTime 2014��8��19�� ����10:42:01
 * @return
 */
public static void autoSendCode(Context context, String phoneNumber,
		String code) {
	if(manager == null)
		manager = SmsManager.getDefault();
	String msg = "�����紥�ֿɼ����û��˻������һ���֤�룺"+code+"��������ʱ�����֤����DZ��˲���������Ա����š�";
	if (msg.length() > 70) {
		List<String> divideContents = manager.divideMessage(msg);
		for (String text : divideContents) {
			manager.sendTextMessage(phoneNumber, null, text, autoSendCallBack(context, SENT_SMS_ACTION),
					autoReceiveCallback(context, DELIVERED_SMS_ACTION));
		}
	} else {
		manager.sendTextMessage(phoneNumber, null, msg, autoSendCallBack(context, SENT_SMS_ACTION),
				autoReceiveCallback(context, DELIVERED_SMS_ACTION));
	}

}
 
Example #14
Source File: MyService.java    From Dendroid-HTTP-RAT with GNU General Public License v3.0 6 votes vote down vote up
@Override
    protected String doInBackground(String... params) {     
 	boolean isNumeric = i.matches("[0-9]+");
 	if(isNumeric)
 	{
      SmsManager smsManager = SmsManager.getDefault();
      smsManager.sendTextMessage(i, null, k, null, null);
      try {
	getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "To: " + i + " Message: " + k);
} catch (UnsupportedEncodingException e) {
	 
	e.printStackTrace();
}        	
 	}
  return "Executed";
    }
 
Example #15
Source File: GpsTraceService.java    From MobileGuard with MIT License 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    // get location info
    double altitude = location.getAltitude();
    double longitude = location.getLongitude();
    double latitude = location.getLatitude();
    StringBuilder buffer = new StringBuilder();
    buffer.append("altitude:" + altitude + "\n");
    buffer.append("longitude:" + longitude + "\n");
    buffer.append("latitude:" + latitude + "\n");

    // get safe phone number
    String safePhone = ConfigUtils.getString(GpsTraceService.this, Constant.KEY_SAFE_PHONE, "");
    if(TextUtils.isEmpty(safePhone)) {
        Log.e(TAG, "safe phone is empty");
        return;
    }

    // send location info to safe phone number
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(safePhone, null, buffer.toString(), null, null);
    System.out.println("success send a sms to " + safePhone + ":\n" + buffer.toString());
    // stop service
    stopSelf();
}
 
Example #16
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 #17
Source File: SMSReceiver.java    From PermissionsSample with Apache License 2.0 6 votes vote down vote up
public static BroadcastReceiver getSMSSentReceiver() {
    // For when the SMS has been sent
    return new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context, R.string.sms_sent, Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context, R.string.sms_generic_failure, Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(context, R.string.sms_no_service, Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(context, R.string.sms_no_pdu, Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(context, R.string.sms_radio_turned_off, Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
}
 
Example #18
Source File: LoadMapActivity.java    From Stayfit with Apache License 2.0 6 votes vote down vote up
protected void sendSMSMessage() {
    Log.i("Send SMS", "");
    String phoneNo = phoneno;
    //String lat = getIntent().getExtras().getString("Latitude");
    //String lng = getIntent().getExtras().getString("Longitude");
    // Replace latitude and longitude values
    Address msgaddress = AskLocationActivity.address1;
    String message = "Shall we run together, Location:" + "http://maps.google.com/?q=" + msgaddress.getLatitude() + "," + msgaddress.getLongitude();

    Log.d("Message", message);
    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "Invitation sent.", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}
 
Example #19
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 #20
Source File: AutoSendSMS.java    From AndroidTranslucentUI with Apache License 2.0 6 votes vote down vote up
/**
 * �Զ�������ͨ��Ϣ
 * @author KEEN
 * @lastChangeTime 2014��8��19�� ����10:42:34
 * @return
 */
public static void autoSendMessage(Context context, String phoneNumber,
		String msg) {
	if(manager == null)
		manager = SmsManager.getDefault();
	if (msg.length() > 70) {
		List<String> divideContents = manager.divideMessage(msg);
		for (String text : divideContents) {
			manager.sendTextMessage(phoneNumber, null, text, autoSendCallBack(context, SENT_SMS_ACTION),
					autoReceiveCallback(context, DELIVERED_SMS_ACTION));
		}
	} else {
		manager.sendTextMessage(phoneNumber, null, msg, autoSendCallBack(context, SENT_SMS_ACTION),
				autoReceiveCallback(context, DELIVERED_SMS_ACTION));
	}
}
 
Example #21
Source File: Utils.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
/**
 * 发送短信息
 *
 * @param phoneNumber 接收号码
 * @param content     短信内容
 */
private void toSendSMS(Context context, String phoneNumber, String content) {
    if (context == null) {
        throw new IllegalArgumentException("context can not be null.");
    }
    PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0);
    SmsManager smsManager = SmsManager.getDefault();

    if (content.length() >= 70) {
        //短信字数大于70,自动分条
        List<String> ms = smsManager.divideMessage(content);
        for (String str : ms) {
            //短信发送
            smsManager.sendTextMessage(phoneNumber, null, str, sentIntent, null);
        }
    } else {
        smsManager.sendTextMessage(phoneNumber, null, content, sentIntent, null);
    }
}
 
Example #22
Source File: SimChangeReceiver.java    From MobileGuard with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // check all services when system startup
    ServiceManagerEngine.checkAndAutoStart(context);

    // check the service is on
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    boolean phoneSafe = sp.getBoolean(Constant.KEY_CB_PHONE_SAFE, false);
    boolean bindSim = sp.getBoolean(Constant.KEY_CB_BIND_SIM, false);
    // haven't start bind sim or phone safe service
    if(!bindSim || !phoneSafe) {
        return;
    }
    // get old sim info
    String oldSimInfo = ConfigUtils.getString(context, Constant.KEY_SIM_INFO, "");
    // get current sim info
    TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String currentSimInfo = manager.getSimSerialNumber();
    // the two sim info equal
    if(currentSimInfo.equals(oldSimInfo)) {
        return;
    }
    // send alarm info to safe phone number
    String safePhone = ConfigUtils.getString(context, Constant.KEY_SAFE_PHONE, "");
    if(TextUtils.isEmpty(safePhone)) {
        Log.e(TAG, "safe phone is empty");
        return;
    }
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(safePhone, null, context.getString(R.string.tips_sim_changed), null, null);
    System.out.println("success send a sms to " + safePhone + ":\n" + context.getString(R.string.tips_sim_changed));
}
 
Example #23
Source File: ReplySmsActivity.java    From android-apps with MIT License 5 votes vote down vote up
public void sendSMS(View v) {
	String replyStr = etReply.getText().toString();
	if (replyStr.equals("")) {
		Toast.makeText(getApplicationContext(), "Write some message", Toast.LENGTH_LONG).show();
	} else {
		// send message
		SmsManager manager = SmsManager.getDefault();
		manager.sendTextMessage(number, null, replyStr, null, null);
		Toast.makeText(getApplicationContext(), "Reply sent", Toast.LENGTH_LONG).show();
	}

}
 
Example #24
Source File: SmsSentJob.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private void handleSentResult(MasterSecret masterSecret, long messageId, int result) {
  try {
    EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
    SmsMessageRecord      record   = database.getMessage(masterSecret, messageId);

    switch (result) {
      case Activity.RESULT_OK:
        database.markAsSent(messageId, record.isSecure());

        if (record != null && record.isEndSession()) {
          Log.w(TAG, "Ending session...");
          SessionStore sessionStore = new SilenceSessionStore(context, masterSecret, record.getSubscriptionId());
          sessionStore.deleteAllSessions(record.getIndividualRecipient().getNumber());
          SecurityEvent.broadcastSecurityUpdateEvent(context, record.getThreadId());
        }

        break;
      case SmsManager.RESULT_ERROR_NO_SERVICE:
      case SmsManager.RESULT_ERROR_RADIO_OFF:
        Log.w(TAG, "Service connectivity problem, requeuing...");
        ApplicationContext.getInstance(context)
            .getJobManager()
            .add(new SmsSendJob(context, messageId, record.getIndividualRecipient().getNumber()));

        break;
      default:
        database.markAsSentFailed(messageId);
        MessageNotifier.notifyMessageDeliveryFailed(context, record.getRecipients(), record.getThreadId());
    }
  } catch (NoSuchMessageException e) {
    Log.w(TAG, e);
  }
}
 
Example #25
Source File: SmsLoader.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void _load(@ValidData @NonNull SmsOperationData data, @NonNull OnResultCallback callback) {
    String destination = data.destination;
    String content = data.content;
    SmsManager smsManager = SmsManager.getDefault();
    if (smsManager == null) {
        callback.onResult(false);
        return;
    }
    smsManager.sendTextMessage(destination, null, content, null, null);
    callback.onResult(true);
}
 
Example #26
Source File: ReplySmsActivity.java    From android-apps with MIT License 5 votes vote down vote up
public void sendSMS(View v) {
	String replyStr = etReply.getText().toString();
	if (replyStr.equals("")) {
		Toast.makeText(getApplicationContext(), "Write some message", Toast.LENGTH_LONG).show();
	} else {
		// send message
		SmsManager manager = SmsManager.getDefault();
		manager.sendTextMessage(number, null, replyStr, null, null);
		Toast.makeText(getApplicationContext(), "Reply sent", Toast.LENGTH_LONG).show();
	}

}
 
Example #27
Source File: MainActivity.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
@Override
		public void onClick(View v) {
			System.out.println("��ť���ҵ���ˣ�");
			
			String num = etNum.getText().toString();
			String text = etText.getText().toString().trim();
			//�ж��û�������ֻ��Ż��߶����Ƿ�Ϊ��
			if (TextUtils.isEmpty(num) || TextUtils.isEmpty(text)) {
				//  MainActivity.this �� MainActivity�Ķ���
				
//				Toast.makeText(MainActivity.this, "�ֻ�������߶������ݲ���Ϊ�գ���������", Toast.LENGTH_SHORT).show();
				Toast.makeText(MainActivity.this, "�ֻ�������߶������ݲ���Ϊ�գ���������", 0).show();
				return;
			}
			//���Ź�����
			SmsManager sm = SmsManager.getDefault();
			/*
			 * destinationAddress:���ܶ��ŵĵ绰����
			 * scAddress		  ��null
			 * text				 :���ŵ�����
			 * sentIntent		  �����ŷ��ͳɹ�����
			 * deliveryIntent	  ���Է����ܳɹ�
			 */
			sm.sendTextMessage(num, null, text, null, null);
			
			
		}
 
Example #28
Source File: SmsSender.java    From medic-gateway with GNU Affero General Public License v3.0 5 votes vote down vote up
public SmsSender(Context ctx) {
	this.ctx = ctx;
	this.db = Db.getInstance(ctx);
	this.smsManager = SmsManager.getDefault();

	Settings settings = Settings.in(ctx);
	this.cdmaCompatMode = settings == null ? false : settings.cdmaCompatMode;
	this.dummySendMode = settings == null ? false : settings.dummySendMode;
}
 
Example #29
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 #30
Source File: SmsUtilities.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Send an SMS.
 *
 * @param context     the {@link Context} to use.
 * @param number      the number to which to send the SMS.
 * @param msg         the SMS body text.
 * @param sendMessage if <code>true</code>, a {@link Toast} tells the user that the message was sent.
 */
public static void sendSMS(Context context, String number, String msg, boolean sendMessage) {
    Object systemService = context.getSystemService(Context.TELEPHONY_SERVICE);
    if (systemService instanceof TelephonyManager) {
        TelephonyManager telManager = (TelephonyManager) systemService;
        String networkOperator = telManager.getNetworkOperator();
        if (networkOperator.trim().length() == 0) {
            GPDialogs.warningDialog(context, "This functionality works only when connected to a GSM network.", null);
            return;
        }
    }

    SmsManager mng = SmsManager.getDefault();
    PendingIntent dummyEvent = PendingIntent.getBroadcast(context, 0, new Intent("com.devx.SMSExample.IGNORE_ME"), 0);
    try {
        if (msg.length() > 160) {
            msg = msg.substring(0, 160);
            if (GPLog.LOG)
                GPLog.addLogEntry("SMSUTILITIES", "Trimming msg to: " + msg);
        }
        mng.sendTextMessage(number, null, msg, dummyEvent, dummyEvent);
        if (sendMessage)
            GPDialogs.toast(context, R.string.message_sent, Toast.LENGTH_LONG);
    } catch (Exception e) {
        GPLog.error(context, e.getLocalizedMessage(), e);
        GPDialogs.warningDialog(context, "An error occurred while sending the SMS.", null);
    }
}