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

The following examples show how to use android.telephony.SmsManager#getDefault() . 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: 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: 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 4
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 5
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 6
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 7
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 8
Source File: ControlService.java    From deskcon-android with GNU General Public License v3.0 5 votes vote down vote up
public void sendSMS(String data) throws JSONException {
	JSONObject smsjobject = new JSONObject(data);
   	String number = smsjobject.getString("number");
   	String message = smsjobject.getString("message");
   	SmsManager smsManager = SmsManager.getDefault();
   	
	smsManager.sendTextMessage(number, null, message, null, null);
	storeSMS(number,message);
	
	SMSToastMessage.show();		
}
 
Example 9
Source File: MainActivity.java    From OpenCircle with GNU General Public License v3.0 5 votes vote down vote up
public void sendSMSNewContact(String name, String phone, String messageString)
{
    Log.d("sendSMSNewContact", messageString);
    if (!TextUtils.isEmpty(phone)) {

        SmsManager smsManager = SmsManager.getDefault();

        isRegisterReceiver = true;

        String action = Constants.ACTION_SENT_SMS_CONTACT + "-" + name;
        PendingIntent sentPendingIntent = PendingIntent
                .getBroadcast(this, 0, new Intent(action), 0);

        registerReceiver(broadcastReceiverSentSMS, new IntentFilter(action));

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

        for (int p = 0; p < splitMessage.size(); p++) {
            if (p == 0) {
                smsManager.sendTextMessage(phone, null, splitMessage.get(p), sentPendingIntent,
                        null);
            } else {
                smsManager.sendTextMessage(phone, null, splitMessage.get(p), null, null);
            }
        }
    }

}
 
Example 10
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 11
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 12
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * sms
 */
private void sms(String number) {
	
   	Util.logDebug("sms()");
   	
	SmsManager smsManager = SmsManager.getDefault();
	smsManager.sendTextMessage(number, null, "Message from ownmdm", null, null);		
}
 
Example 13
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 14
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 15
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 16
Source File: SmsSendJob.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private SmsManager getSmsManagerFor(int subscriptionId) {
  Log.w(TAG, "getSmsManagerFor(" + subscriptionId + ")");
  if (Build.VERSION.SDK_INT >= 22 && subscriptionId != -1) {
    return SmsManager.getSmsManagerForSubscriptionId(subscriptionId);
  } else {
    return SmsManager.getDefault();
  }
}
 
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: CallAndSmsUtils.java    From BigApp_Discuz_Android with Apache License 2.0 4 votes vote down vote up
public static void sendSMS(Context context, Intent intent,
		String phonenumber, String msg) {// 发送短信的类
	PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
	SmsManager sms = SmsManager.getDefault();
	sms.sendTextMessage(phonenumber, null, msg, pi, null);// 发送信息到指定号码
}
 
Example 19
Source File: SmsSnippet.java    From mobly-bundled-snippets with Apache License 2.0 4 votes vote down vote up
public SmsSnippet() {
    this.mContext = InstrumentationRegistry.getInstrumentation().getContext();
    this.mSmsManager = SmsManager.getDefault();
}
 
Example 20
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);
}