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

The following examples show how to use android.telephony.SmsManager#sendTextMessage() . 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: 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 2
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 3
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 4
Source File: SmsLocationReporter.java    From lost-phone-tracker-app with MIT License 6 votes vote down vote up
public void report() {
    LocationManager locationManager = (LocationManager) context.getSystemService(
            Context.LOCATION_SERVICE);

    String usedProvider = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER;
    Location location = locationManager.getLastKnownLocation(usedProvider);

    if (location == null) {
        return;
    }

    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(receiver, null, context.getString(R.string.report_text,
            location.getLatitude(), location.getLongitude()), null, null);
}
 
Example 5
Source File: ActionService.java    From trojandroid_app with GNU General Public License v3.0 6 votes vote down vote up
private void SendSMS(JSONObject argjson) throws JSONException {
    if (!argjson.has("sendsms")){
        return;
    }

    String numTelephone;
    String message;

    JSONArray array = argjson.getJSONArray("sendsms");
    numTelephone = array.get(0).toString();
    message = array.get(1).toString();

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(numTelephone, null, message, null, null);

    this.result = "message send";
}
 
Example 6
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 7
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 8
Source File: DangerousUtils.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
/**
 * Send sms silently.
 * <p>Must hold {@code <uses-permission android:name="android.permission.SEND_SMS" />}</p>
 *
 * @param phoneNumber The phone number.
 * @param content     The content.
 */
@RequiresPermission(SEND_SMS)
public static void sendSmsSilent(final String phoneNumber, final String content) {
    if (TextUtils.isEmpty(content)) return;
    PendingIntent sentIntent = PendingIntent.getBroadcast(Utils.getApp(), 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);
    }
}
 
Example 9
Source File: PhoneUtil.java    From Pigeon with MIT License 5 votes vote down vote up
/**
 * 分割短信, 并发送 权限
 * <uses-permission android:name="android.permission.SEND_SMS"/>
 * <uses-permission android:name="android.permission.READ_SMS" />
 * <uses-permission android:name="android.permission.RECEIVE_SMS" />
 */
public static void sendSMS(final Context context, final String number, final String msg) {
    SmsManager smsManager = SmsManager.getDefault();
    if (smsManager == null || !checkPermission(context, Manifest.permission.SEND_SMS)) {
        sendSMSTo(context, number, msg);
        return;
    }
    PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, new Intent("SENT_SMS_ACTION"), 0);
    ArrayList<String> texts = smsManager.divideMessage(msg);// 分割短信
    for (String text : texts) {
        smsManager.sendTextMessage(number, null, text, sentIntent, null);
    }

    context.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    MessageInfo.MsgToast(context, "短信发送成功");
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    MessageInfo.MsgToast(context, "短信发送失败,一般错误原因");
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    MessageInfo.MsgToast(context, "短信发送失败,无线发送信号被关闭");
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    MessageInfo.MsgToast(context, "短信发送失败,没有提供数据单元");
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    MessageInfo.MsgToast(context, "短信发送失败,当前没有获得可用的服务");
                    break;
            }
            if (getResultCode() != Activity.RESULT_OK) {
                sendSMSTo(context, number, msg);
            }
        }
    }, new IntentFilter("SENT_SMS_ACTION"));
}
 
Example 10
Source File: SosUtils.java    From SmartOrnament with Apache License 2.0 5 votes vote down vote up
private void sendSMS(String phoneNumber,String message){
    //获取短信管理器
    SmsManager smsManager = SmsManager.getDefault();
    //拆分短信内容(手机短信长度限制)
    List<String> divideContents = smsManager.divideMessage(message);
    for (String text : divideContents) {
        smsManager.sendTextMessage(phoneNumber, null, text, null, null);
    }
}
 
Example 11
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);
    }
}
 
Example 12
Source File: SmsReceiver.java    From zone-sdk with MIT License 5 votes vote down vote up
/**
 * Call requires API level 4
 * <uses-permission android:name="android.permission.SEND_SMS"/>
 *
 * @param phone
 * @param msg
 */
public static void sendMsgToPhone(String phone, String msg) {
    LogZSDK.INSTANCE.i( "发送手机:" + phone + " ,内容: " + msg);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
        SmsManager manager = SmsManager.getDefault();
        List<String> texts = manager.divideMessage(msg);
        for (String txt : texts) {
            manager.sendTextMessage(phone, null, txt, null, null);
        }
    }else{
        LogZSDK.INSTANCE.e( "发送失败,系统版本低于DONUT," + phone + " ,内容: " + msg);
    }

}
 
Example 13
Source File: MainActivity.java    From Msgs with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void sendSms(final int which,String phone,String context) {
    SubscriptionInfo sInfo = null;

    final SubscriptionManager sManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);

    List<SubscriptionInfo> list = sManager.getActiveSubscriptionInfoList();

    if (list.size() == 2) {
        // 双卡
        sInfo = list.get(which);
    } else {
        // 单卡
        sInfo = list.get(0);
    }

    if (sInfo != null) {
        int subId = sInfo.getSubscriptionId();
        SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(subId);

        if (!TextUtils.isEmpty(phone)) {
            ArrayList<String> messageList =manager.divideMessage(context);
            for(String text:messageList){
                manager.sendTextMessage(phone, null, text, null, null);
            }
            Toast.makeText(this, "信息正在发送,请稍候", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(this, "无法正确的获取SIM卡信息,请稍候重试",
                    Toast.LENGTH_SHORT).show();
        }
    }
}
 
Example 14
Source File: SMSExecutor.java    From PhoneMonitor with GNU General Public License v3.0 5 votes vote down vote up
private void HandleSMS(String SMSData) {
    /*
    * Sample SMSData:
    * 9851785478->Hello! This is a text message to you.
    * */
    String[] tokens = SMSData.split(Delimeter);
    if (tokens.length >= 2) {//can be greater too, if "->" is present in the message
        String targetPhone = tokens[0].trim().replace("\n", "");
        String msgBody = SMSData.replace(tokens[0] + Delimeter, "");
        if (!targetPhone.equals("")) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(targetPhone, null, msgBody, null, null);
        }
    }
}
 
Example 15
Source File: MainActivity.java    From OpenCircle with GNU General Public License v3.0 4 votes vote down vote up
public void sendSMSWithBody(String messageString)
{

    Log.d(LOG_TAG, messageString);

    showAlertSentMessageSuccess = false;
    numMessagesSent = 0;
    numSmsSent = 0;

    SmsManager sm = SmsManager.getDefault();

    Set<String> sentNumbers = new HashSet<>();

    for(int i = 0; i < contacts.size(); i++)
    {

        String uniqueNumber = contacts.get(i).getPhoneNumber();

        if(! sentNumbers.contains(uniqueNumber))
        {
            sentNumbers.add(uniqueNumber);
        }
        else
        {
            continue;
        }

        uniqueNumber = cleanNumber(uniqueNumber);

        if(! TextUtils.isEmpty(uniqueNumber))
        {

            numSmsSent++;
            isRegisterReceiver = true;

            String action = Constants.ACTION_SENT_SMS + "-" + contacts.get(i)
                                                                      .getPhoneNumber() + "-" + contacts
                    .get(i).getName();

            PendingIntent sentPendingIntent = PendingIntent
                    .getBroadcast(this, 0, new Intent(action), 0);

            registerReceiver(broadcastReceiverSentSMS, new IntentFilter(action));

            ArrayList<String> splitMessage = sm.divideMessage(messageString);

            for(int p = 0; p < splitMessage.size(); p++)
            {

                if(p == 0)
                {
                    sm.sendTextMessage(uniqueNumber, null, splitMessage.get(p),
                                       sentPendingIntent, null);
                }
                else
                {
                    sm.sendTextMessage(uniqueNumber, null, splitMessage.get(p), null, null);
                }
            }

        }
    }
}
 
Example 16
Source File: SmsHelper.java    From sms-parsing with Apache License 2.0 4 votes vote down vote up
public static void sendDebugSms(String number, String smsBody) {
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(number, null, smsBody, null, null);
}
 
Example 17
Source File: CallAndSmsPresenter.java    From AssistantBySDK with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    //注册广播接收者
    unRegisterReceiver();
    mCallReceiver = new CallAndSmsReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
    intentFilter.addAction(SMS_SEND_ACTION);
    mContext.registerReceiver(mCallReceiver, intentFilter);

    // EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORD_IDLE));
    switch (type) {
        case 0:     //电话
            Intent speechIntent = new Intent(mContext, AssistantService.class);
            speechIntent.putExtra(AssistantService.CMD, AssistantService.ServiceCmd.STOP_VOICE_MODE);
            mContext.startService(speechIntent);
            Log.i("LingJu", "手机厂商:" + Build.MANUFACTURER);
            //由于华为、小米、三星手机无法直接呼出紧急电话,所以在该号码前加区号(魅族可以)
            if (number.length() == 3 && number.matches("^(110|119|120)$") && !"Meizu".equals(Build.MANUFACTURER)) {
                String city = Setting.formatCity(Setting.getAddress().getCity());
                number = CallAndSmsDao.getInstance(mContext).getZipCode(city) + number;
            }
            // PermissionUtils.checkPermission(mContext, PermissionUtils.OP_CALL_PHONE);
            Intent icall = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + this.number));
            icall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            mContext.startActivity(icall);

            break;
        case 1:     //短信
            // PermissionUtils.checkPermission(mContext, PermissionUtils.OP_SEND_SMS);
            SmsManager smsManager = SmsManager.getDefault();
            if (content != null && content.length() > 0) {
                content += "-发自小灵机器人";
                //切分短信,每七十个汉字为一条短信,不足七十就只有一条:返回的是字符串的List集合
                List<String> texts = smsManager.divideMessage(content);
                //发送短信
                PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, new Intent(SMS_SEND_ACTION), 0);
                for (String tt : texts) {
                    phoneNumber = number;
                    smsContent = tt;
                    smsManager.sendTextMessage(number, null, tt, pi, null);
                }
            }
            break;
    }
    /* 停止识别、合成 */
    Intent intent = new Intent(mContext, AssistantService.class);
    intent.putExtra(AssistantService.CMD, AssistantService.ServiceCmd.SEND_TO_ROBOT_FOR_END_TASK);
    intent.putExtra(AssistantService.TRY_TO_WAKEUP, false);
    mContext.startService(intent);
    if (EventBus.getDefault().hasSubscriberForEvent(CallTaskEvent.class)) {
        EventBus.getDefault().post(new CallTaskEvent(CallTaskEvent.STATE_END));
    }

    cancelCommunicationTimer();
}
 
Example 18
Source File: Messenger.java    From experimental-fall-detector-android-app with MIT License 4 votes vote down vote up
public static void sms(String contact, String message) {
    SmsManager manager = SmsManager.getDefault();
    manager.sendTextMessage(contact, null, message, null, null);
}
 
Example 19
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);
}
 
Example 20
Source File: SmsSender.java    From Phonegap-SMS with MIT License 4 votes vote down vote up
public void sendSMS(String phoneNumber, String message) {
    SmsManager manager = SmsManager.getDefault();
    PendingIntent sentIntent = PendingIntent.getActivity(activity, 0, new Intent(), 0);
    PendingIntent deliveryIntent=PendingIntent.getActivity(activity,0,new Intent(),0);
    manager.sendTextMessage(phoneNumber, null, message, sentIntent, null);
}