Example usage for android.telephony SmsManager getDefault

List of usage examples for android.telephony SmsManager getDefault

Introduction

In this page you can find the example usage for android.telephony SmsManager getDefault.

Prototype

public static SmsManager getDefault() 

Source Link

Document

Get the SmsManager associated with the default subscription id.

Usage

From source file:com.xortech.sender.SmsReceiver.java

public void onReceive(final Context ctx, Intent intent) {
    // GET SMS MAP FROM INTENT
    Bundle extras = intent.getExtras();/*from   www.  j  a  v a 2s  . c  o  m*/
    context = ctx;

    // GPS INSTANCE
    gps = new GPSTracker(context);

    // LOAD PREFERENCES
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    secretCode = preferences.getString("secretCode", DEFAULT_CODE);
    tagID = preferences.getString("tagID", DEFAULT_TAGID);
    senderEnabled = preferences.getBoolean("senderEnabled", true);

    if (extras != null) {

        // GET THE RECEIVED SMS ARRAY
        Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);

        for (int i = 0; i < smsExtra.length; ++i) {

            // GET THE MESSAGE
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);

            // PARSE THE MESSAGE BODY
            String body = sms.getMessageBody().toString();
            String address = sms.getOriginatingAddress();
            long time = System.currentTimeMillis();

            // GET COORDINATES AND SEND A MESSAGE
            gps.getLocation();

            latitude = String.valueOf(Math.round(FIVE_DIGIT * gps.getLatitude()) / FIVE_DIGIT);
            longitude = String.valueOf(Math.round(FIVE_DIGIT * gps.getLongitude()) / FIVE_DIGIT);
            location = "Tag_ID:" + tagID + ":Location:" + latitude + "," + longitude;
            googleString = GOOGLE_STRING + latitude + "," + longitude + "(" + tagID + ")";

            if (body.equals(SECRET_LOCATION_A + secretCode)) {
                if (senderEnabled) {
                    if (latitude.equals("0.0") | longitude.equals("0.0")) {
                        SmsManager.getDefault().sendTextMessage(address, null, NO_COORDS + tagID, null, null);
                    } else {
                        SmsManager.getDefault().sendTextMessage(address, null, googleString, null, null);
                    }
                }

                this.abortBroadcast();
            } else if (body.equals(SECRET_LOCATION_B + secretCode)) {
                if (senderEnabled) {
                    if (latitude.equals("0.0") | longitude.equals("0.0")) {
                        SmsManager.getDefault().sendTextMessage(address, null, NO_COORDS + tagID, null, null);
                    } else {
                        SmsManager.getDefault().sendTextMessage(address, null, location, null, null);
                    }
                }

                this.abortBroadcast();
            } else if (body.contains("Tag_ID:")) {
                // ADD TO DATABASE
                MsgDatabaseHandler dbHandler = new MsgDatabaseHandler(context);

                // VERIFY IF THE TAG EXISTS IN THE ARRAY
                String addressExists = VerifyTagExist(address);

                String[] splitBody = body.split(":");
                String tag = splitBody[1];
                tag.trim();
                String coords = splitBody[3];
                String[] splitCoords = coords.split(",");
                String lat = splitCoords[0];
                lat.trim();
                String lon = splitCoords[1];
                lon.trim();
                String _time = String.valueOf(time);
                String toastMsg = null;

                // CHECK IF THE ADDRESS EXISTS FOR NAMING PURPOSES
                if (addressExists == null) {
                    dbHandler.Add_Message(new MessageData(tag, address, lat, lon, _time));
                    toastMsg = "Response Received: " + tag;
                } else {
                    dbHandler.Add_Message(new MessageData(addressExists, address, lat, lon, _time));
                    toastMsg = "Response Received: " + addressExists;
                }

                dbHandler.close();

                Toast.makeText(context, toastMsg, Toast.LENGTH_LONG).show();

                this.abortBroadcast();
            } else if (body.contains("Panic!")) {

                // OVERRIDE THE SILENT FEATURE
                AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                int max = audio.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                audio.setStreamVolume(AudioManager.STREAM_RING, max,
                        AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

                // DEFINE THE NOTIFICATION MANAGER
                notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);

                // START A TIMER
                mytimer = new Timer(true);

                // SOUND LOCATION ALARM
                soundUri = Uri.parse(BEGIN_PATH + context.getPackageName() + FILE_PATH);

                // DISPLAY TAG ID FOR EMERGENCY
                String[] splitBody = body.split("\n");
                String fieldTag = splitBody[1];
                String[] splitTag = fieldTag.split(":");

                emergencyTag = splitTag[1].trim();

                // TIMER FOR NOTIFICATIONS
                mytask = new TimerTask() {
                    public void run() {
                        // RUN NOTIFICATION ON TIMER
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                                .setSmallIcon(R.drawable.emergency).setContentTitle(PANIC_TXT)
                                .setContentText(emergencyTag + UNDER_DURRESS).setSound(soundUri); //This sets the sound to play

                        // DISPLAY THE NOTIFICATION
                        notificationManager.notify(0, mBuilder.build());
                    }
                };
                // START TIMER AFTER 5 SECONDS
                mytimer.schedule(mytask, FIVE_SECONDS);
            }
        }
    }

    // CLEAR THE CACHE ON RECEIVING A MESSAGE
    try {
        MyUpdateReceiver.trimCache(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.example.android.smsmessaging.MainActivity.java

/**
 * Defines a string (destinationAddress) for the phone number
 * and gets the input text for the SMS message.
 * Uses SmsManager.sendTextMessage to send the message.
 * Before sending, checks to see if permission is granted.
 *
 * @param view View (message_icon) that was clicked.
 *//*  www. j av a  2 s .co m*/
public void smsSendMessage(View view) {
    EditText editText = (EditText) findViewById(R.id.editText_main);
    // Set the destination phone number to the string in editText.
    String destinationAddress = editText.getText().toString();
    // Find the sms_message view.
    EditText smsEditText = (EditText) findViewById(R.id.sms_message);
    // Get the text of the sms message.
    String smsMessage = smsEditText.getText().toString();
    // Set the service center address if needed, otherwise null.
    String scAddress = null;
    // Set pending intents to broadcast
    // when message sent and when delivered, or set to null.
    PendingIntent sentIntent = null, deliveryIntent = null;
    // Check for permission first.
    checkForSmsPermission();
    // Use SmsManager.
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(destinationAddress, scAddress, smsMessage, sentIntent, deliveryIntent);
}

From source file:com.hari.autotasx.GeofenceTransitionsIntentService.java

@Override
protected void onHandleIntent(Intent intent) {

    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        String errorMessage = GeofenceErrorMessages.getErrorString(this, geofencingEvent.getErrorCode());
        // Log.e(TAG, errorMessage);
        return;/*w w  w .ja v  a 2  s. co  m*/
    }

    int geofenceTransition = geofencingEvent.getGeofenceTransition();
    int smsDb = 0;
    int wifiDb = 0;
    int silDb = 0;
    int RemDb = 0;
    int blueDb = 0;
    int carDb = 0;
    String remMsgDb = null;
    int RemDb_carPark = 0;
    String remMsgDb_carPark = null;
    //Creating database object to fetch values
    ManageDB autodb = new ManageDB(this);
    autodb.open();

    if (!CarParkService.car_flag_static) {
        Cursor cursor = autodb.getEntry(ActionFragment.geoFence);
        cursor.moveToFirst();

        //System.out.println("cursor count"+cursor.getCount());

        //Log.i("logcat",cursor.getString(0)+", "+cursor.getString(1)+" , "+cursor.getString(2));
        smsDb = cursor.getInt(5);
        wifiDb = cursor.getInt(6);
        silDb = cursor.getInt(7);
        RemDb = cursor.getInt(8);
        remMsgDb = cursor.getString(9);
        blueDb = cursor.getInt(10);
        carDb = cursor.getInt(11);

        cursor.close();

    } else {
        Cursor cursor_carpark = autodb.getEntryCarPark(CarParkService.geofence_carpark);
        cursor_carpark.moveToFirst();

        carDb = cursor_carpark.getInt(11);
        remMsgDb_carPark = cursor_carpark.getString(9);

        cursor_carpark.close();
    }
    autodb.close();

    //Checking Enter/Exit transitions
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        String geofenceTransitionDetails = getGeofenceTransitionDetails(this, geofenceTransition,
                triggeringGeofences);
        System.out.println("smsdb" + smsDb);
        if (RemDb == 1) {
            sendNotification(geofenceTransitionDetails, remMsgDb);
        }
        if (carDb == 1) {
            sendNotification(geofenceTransitionDetails, remMsgDb_carPark);
        }
        //Perform actions if set on Actions set
        if (silDb == 1) {
            Toast.makeText(this, "silent", Toast.LENGTH_SHORT).show();
            AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
            am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

        }

        if (wifiDb == 1) {
            WifiManager wifiManager = (WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);
        }

        if (blueDb == 1) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();
            }
        }
        if (smsDb == 1) {
            Toast.makeText(this, "inside sendsms()", Toast.LENGTH_SHORT).show();
            SmsManager sm = SmsManager.getDefault();
            System.out.printf("sm", sm);
            sm.sendTextMessage(ActionFragment.smsNo, null,
                    "Hi, I am in " + ActionFragment.geoFence.getNameLoc() + " now!!!!", null, null);
        }
        if (carDb == 1) {
            Intent mapIntent = new Intent(this, CarParkMap.class);
            mapIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

    } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        String geofenceTransitionDetails = getGeofenceTransitionDetails(this, geofenceTransition,
                triggeringGeofences);
        if (silDb == 1) {
            Toast.makeText(this, "general", Toast.LENGTH_SHORT).show();
            AudioManager am1 = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
            am1.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

        if (wifiDb == 1) {
            WifiManager wifiManager1 = (WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager1.setWifiEnabled(false);
        }
        if (blueDb == 1) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.disable();
            }
        }
        if (smsDb == 1) {
            Toast.makeText(this, "inside sendsms()", Toast.LENGTH_SHORT).show();
            SmsManager sm = SmsManager.getDefault();
            System.out.printf("smsNo :" + ActionFragment.smsNo);
            //fetch
            sm.sendTextMessage(ActionFragment.smsNo, null,
                    "Hi, I am outside " + ActionFragment.geoFence.getNameLoc() + " now !!!", null, null);
        }
        if (RemDb == 1) {
            sendNotification(geofenceTransitionDetails, remMsgDb);
        }

    }

}

From source file:in.codehex.arrow.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case Config.REQUEST_SPEECH_INPUT:
        if (resultCode == RESULT_OK && data != null) {
            ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (result.get(0).equalsIgnoreCase("emergency")) {
                String phone = userPreferences.getString(Config.KEY_PREF_PHONE, null);
                String message = "Emergency!\n" + userPreferences.getString(Config.KEY_PREF_NAME, null)
                        + " is at http://maps.google.com/maps?q=" + lat + "," + lng;
                try {
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(phone, null, message, null, null);
                    textToSpeech.speak("Emergency alert sent!", TextToSpeech.QUEUE_FLUSH, null, null);
                } catch (Exception e) {
                    textToSpeech.speak("Unable to send alert message!", TextToSpeech.QUEUE_FLUSH, null, null);
                }// ww  w .j a  va  2  s.  com
            } else if (isDestinationAvailable) {
                if (result.get(0).equalsIgnoreCase("yes")) {
                    processDirection();
                    isDestinationAvailable = false;
                } else {
                    textToSpeech.speak(getString(R.string.prompt_speech_input_initial),
                            TextToSpeech.QUEUE_FLUSH, null, Config.UTTERANCE_ID_INITIAL);
                    isDestinationAvailable = false;
                }
            } else {
                speakData(result.get(0));
            }
        }
        break;
    case Config.REQUEST_CHECK_TTS:
        if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            intent = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(intent);
        }
        break;
    }
}

From source file:org.xwalk.runtime.extension.api.messaging.MessagingSmsManager.java

public void onSmsSegmentInfo(int instanceID, JSONObject jsonMsg) {
    String promise_id = null;//from   ww w. j  a  va2 s  .com
    JSONObject eventBody = null;
    String text = null;
    try {
        promise_id = jsonMsg.getString("_promise_id");
        eventBody = jsonMsg.getJSONObject("data");
        text = eventBody.getString("text");

        if (null == text) {
            Log.e(TAG, "No \"text\" attribute.");
            return;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }

    SmsManager sms = SmsManager.getDefault();
    ArrayList<String> segs = sms.divideMessage(text);
    try {
        JSONObject jsonMsgRet = new JSONObject();
        jsonMsgRet.put("cmd", "msg_smsSegmentInfo_ret");
        jsonMsgRet.put("_promise_id", promise_id);
        JSONObject jsData = new JSONObject();
        jsonMsgRet.put("data", jsData);
        jsData.put("error", false);
        JSONObject jsBody = new JSONObject();
        jsData.put("body", jsBody);
        jsBody.put("segments", segs.size());
        jsBody.put("charsPerSegment", segs.get(0).length());
        jsBody.put("charsAvailableInLastSegment", segs.get(segs.size() - 1).length());

        mMessagingHandler.postMessage(instanceID, jsonMsgRet.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }
}

From source file:com.mattprecious.locnotifier.LocationService.java

private void approachingDestination() {
    Log.d(getClass().getSimpleName(), "Within distance to destination");

    locationManager.removeUpdates(locationListener);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);

    String notifTitle = getString(R.string.notification_alert_title);
    String notifText = getString(R.string.notification_alert_text);

    runningNotification = null;/* w ww  . j  a  v  a  2  s .c o  m*/

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.notification_alert).setContentTitle(notifTitle)
            .setContentText(notifText).setContentIntent(contentIntent).setAutoCancel(true);

    String tone = preferences.getString("tone", null);
    Uri toneUri = (tone == null) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            : Uri.parse(tone);

    notificationBuilder.setSound(toneUri);

    if (preferences.getBoolean("vibrate", false)) {
        int shortVib = 150;
        int shortPause = 150;

        // vibrate 3 short times
        long[] pattern = { 0, shortVib, shortPause, shortVib, shortPause, shortVib, };

        notificationBuilder.setVibrate(pattern);
    }

    notificationBuilder.setLights(0xffff0000, 500, 500);

    Notification notification = notificationBuilder.getNotification();
    if (preferences.getBoolean("insistent", false)) {
        notification.flags |= Notification.FLAG_INSISTENT;
    }

    notificationManager.notify(0, notification);

    // send sms
    if (preferences.getBoolean("sms_enabled", false)) {
        String number = preferences.getString("sms_contact", null);
        String message = preferences.getString("sms_message", null);

        if (number != null && message != null) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, message, null, null);
        }
    }

    stopSelf();
}

From source file:com.tbay.android.FrequentSMS.MainActivity.java

public void sendSMS(View view) {

    EditText Txt = (EditText) findViewById(R.id.SMSText);

    RadioGroup rg = (RadioGroup) findViewById(R.id.whichSMS);
    int rbid = rg.getCheckedRadioButtonId();

    SmsManager smsManager = SmsManager.getDefault();

    switch (rbid) {
    case R.id.Wifi:
        mAppPrefs.Key1_Msg = Txt.getText().toString();
        mAppPrefs.SelectionId = 0;/*from   w  ww.j av  a2  s. c om*/
        smsManager.sendTextMessage(AppConstants.phoneWifi, null, mAppPrefs.Key1_Msg, null, null);
        break;
    case R.id.Aftensmad:
        mAppPrefs.Key2_Msg = Txt.getText().toString();
        mAppPrefs.SelectionId = 1;
        smsManager.sendTextMessage(AppConstants.phoneAnnette, null, mAppPrefs.Key2_Msg, null, null);
        break;
    case R.id.Snart_hjemme:
        mAppPrefs.Key3_Msg = Txt.getText().toString();
        mAppPrefs.SelectionId = 2;
        smsManager.sendTextMessage(AppConstants.phoneAnnette, null, mAppPrefs.Key3_Msg, null, null);
        break;
    case R.id.TestSMS:
        mAppPrefs.Key4_Msg = Txt.getText().toString();
        mAppPrefs.SelectionId = 3;
        smsManager.sendTextMessage(AppConstants.phonePrivate, null, mAppPrefs.Key4_Msg, null, null);
        break;
    }
    mAppPrefs.savePreferences(getApplicationContext());
}

From source file:com.godowondev.MyGcmListenerService.java

private void sendSMS(String phoneNumber, String message) {
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, null, null);
}

From source file:mx.com.neus.juanitovision.GeofenceTransitionsIntentService.java

public void sendSMS(String phoneNo, String msg) {
    try {/*from   ww  w . j  a  v  a2 s.c  o  m*/
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, msg, null, null);
        Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_LONG).show();
    } catch (Exception ex) {
        Toast.makeText(getApplicationContext(), ex.getMessage().toString(), Toast.LENGTH_LONG).show();
        ex.printStackTrace();
    }
}

From source file:com.rjfun.cordova.sms.SMSPlugin.java

private PluginResult sendSMS(JSONArray addressList, String text, CallbackContext callbackContext) {
    Log.d(LOGTAG, ACTION_SEND_SMS);//  w  ww. j a  va2 s .com
    if (this.cordova.getActivity().getPackageManager().hasSystemFeature("android.hardware.telephony")) {
        int n;
        if ((n = addressList.length()) > 0) {
            PendingIntent sentIntent = PendingIntent.getBroadcast((Context) this.cordova.getActivity(), (int) 0,
                    (Intent) new Intent("SENDING_SMS"), (int) 0);
            SmsManager sms = SmsManager.getDefault();
            for (int i = 0; i < n; ++i) {
                String address;
                if ((address = addressList.optString(i)).length() <= 0)
                    continue;
                sms.sendTextMessage(address, null, text, sentIntent, (PendingIntent) null);
            }
        } else {
            PendingIntent sentIntent = PendingIntent.getActivity((Context) this.cordova.getActivity(), (int) 0,
                    (Intent) new Intent("android.intent.action.VIEW"), (int) 0);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.putExtra("sms_body", text);
            intent.setType("vnd.android-dir/mms-sms");
            try {
                sentIntent.send(this.cordova.getActivity().getApplicationContext(), 0, intent);
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "OK"));
    } else {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "SMS is not supported"));
    }
    return null;
}