コード例 #1
0
  /**
   * Sends a text message via SMS. No authentication required. This method is called only when the
   * UseGoogleVoice option is disabled.
   */
  private void sendViaSms() {
    Log.i(TAG, "Sending via built-in Sms");

    ArrayList<String> parts = smsManager.divideMessage(message);
    int numParts = parts.size();
    ArrayList<PendingIntent> pendingIntents = new ArrayList<PendingIntent>();
    for (int i = 0; i < numParts; i++)
      pendingIntents.add(PendingIntent.getBroadcast(activity, 0, new Intent(SENT), 0));

    // Receiver for when the SMS is sent
    BroadcastReceiver sendReceiver =
        new BroadcastReceiver() {
          @Override
          public synchronized void onReceive(Context arg0, Intent arg1) {
            try {
              handleSentMessage(arg0, null, getResultCode(), message);
              activity.unregisterReceiver(this);
            } catch (Exception e) {
              Log.e("BroadcastReceiver", "Error in onReceive for msgId " + arg1.getAction());
              Log.e("BroadcastReceiver", e.getMessage());
              e.printStackTrace();
            }
          }
        };
    // This may result in an error -- a "sent" or "error" message will be displayed
    activity.registerReceiver(sendReceiver, new IntentFilter(SENT));
    smsManager.sendMultipartTextMessage(phoneNumber, null, parts, pendingIntents, null);
  }
コード例 #2
0
ファイル: Sms.java プロジェクト: Ribeiro/alunoce2
  /**
   * Envia um SMS para o numero indicado Obs.: o numero pode ser o do proprio emulador, exemplo:
   * 5554
   *
   * @param context
   * @param numero
   * @param mensagem
   * @return
   */
  public static boolean enviarSms(Context context, String numero, String mensagem) {
    try {
      SmsManager smsManager = SmsManager.getDefault();

      // identifica a chamada
      PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0);

      // Divide a mensagem caso ultrapasse 160 caracteres
      ArrayList<String> messages = smsManager.divideMessage(mensagem);

      // Instancia uma lista de PendingIntent
      ArrayList<PendingIntent> pIntents = new ArrayList<PendingIntent>(messages.size());

      for (int i = 0; i < messages.size(); i++) {
        pIntents.add(pIntent);
      }

      // envia a mensagem binaria
      smsManager.sendMultipartTextMessage(numero, null, messages, pIntents, null);

      return true;

    } catch (Exception e) {
      Log.e(LOG_SMS, "Erro ao enviar sms: " + e.getMessage(), e);
      return false;
    }
  }
コード例 #3
0
  public void send(String phoneNumber, String messageToSent) {

    PhoneNumber number = PhoneNumber.parse(phoneNumber);

    SmsManager sms = SmsManager.getDefault();
    System.out.println("Sending SMS to: " + phoneNumber + ", message: " + messageToSent);

    ArrayList<String> messageArray = sms.divideMessage(messageToSent);
    sms.sendMultipartTextMessage(number.getPhoneNumber(), null, messageArray, null, null);
  }
コード例 #4
0
 @Override
 public void sendMultipartTextMessage(
     String destinationAddress,
     String scAddress,
     ArrayList<String> parts,
     ArrayList<PendingIntent> sentIntents,
     ArrayList<PendingIntent> deliveryIntents) {
   mSmsManager.sendMultipartTextMessage(
       destinationAddress, scAddress, parts, sentIntents, deliveryIntents);
 }
コード例 #5
0
  /** Send one SMS message to the receiver */
  private void sendSms() {

    try {

      if (checkSendPhoneNumber()) {

        final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
        final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

        // Create the setIntent parameter
        Intent sentIntent = new Intent(SENT_SMS_ACTION);
        PendingIntent sentPI =
            PendingIntent.getBroadcast(QuiteSleepApp.getContext(), 0, sentIntent, 0);

        // Create the deliveryIntetn parameter
        Intent deliveryIntent = new Intent(DELIVERED_SMS_ACTION);
        PendingIntent deliverPI =
            PendingIntent.getBroadcast(QuiteSleepApp.getContext(), 0, deliveryIntent, 0);

        SmsManager smsManager = SmsManager.getDefault();

        /* In Nexus One there is a bug (how in htc tatoo) that sent sms
         * using sendTextMessage not found, so i try to send sms by
         * cut into parts (if its necessary) and send using sendMultipartMessage
         */
        ArrayList<String> multipartSmsText = smsManager.divideMessage(smsText);
        int smsSize = multipartSmsText.size();

        // Create the arraylist PendingIntents for use it.
        ArrayList<PendingIntent> sentPiList = new ArrayList<PendingIntent>(smsSize);
        ArrayList<PendingIntent> deliverPiList = new ArrayList<PendingIntent>(smsSize);

        for (int i = 0; i < smsSize; i++) {
          sentPiList.add(sentPI);
          deliverPiList.add(deliverPI);
        }

        // Try to send the sms message
        smsManager.sendMultipartTextMessage(
            incomingCallNumber, null, multipartSmsText, sentPiList, deliverPiList);
      }

    } catch (Exception e) {
      Log.e(CLASS_NAME, ExceptionUtils.getString(e));
    }
  }
コード例 #6
0
ファイル: SendSMS.java プロジェクト: binel01/lightSmsAndroid
  /* Called from the GUI to send one message to one destination */
  public boolean sendSMSMessage(String aDestinationAddress, String aMessageText) {

    if (mSMSManager == null) {
      return (false);
    }

    mFragmentList = mSMSManager.divideMessage(aMessageText);
    int fragmentCount = mFragmentList.size();
    if (fragmentCount > 1) {
      Log.d(TAG, "Sending " + fragmentCount + " parts");
      mSMSManager.sendMultipartTextMessage(
          aDestinationAddress, mServiceCentreAddr, mFragmentList, null, null);
    } else {
      Log.d(TAG, "Sendine one part");
      mSMSManager.sendTextMessage(
          aDestinationAddress, mServiceCentreAddr, aMessageText, null, null);
    }

    return true;
  }
コード例 #7
0
  public void sendSMS(String phoneNumber, String message, Context mContext) {
    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
    PendingIntent sentPI =
        PendingIntent.getBroadcast(mContext, 0, new Intent(mContext, SmsSentReceiver.class), 0);
    PendingIntent deliveredPI =
        PendingIntent.getBroadcast(
            mContext, 0, new Intent(mContext, SmsDeliveredReceiver.class), 0);
    try {
      SmsManager sms = SmsManager.getDefault();
      ArrayList<String> mSMSMessage = sms.divideMessage(message);
      for (int i = 0; i < mSMSMessage.size(); i++) {
        sentPendingIntents.add(i, sentPI);
        deliveredPendingIntents.add(i, deliveredPI);
      }
      sms.sendMultipartTextMessage(
          phoneNumber, null, mSMSMessage, sentPendingIntents, deliveredPendingIntents);

    } catch (Exception e) {

      e.printStackTrace();
      Toast.makeText(mContext, "SMS sending failed...", Toast.LENGTH_SHORT).show();
    }
  }
コード例 #8
0
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Location location = locationManager.getLastKnownLocation(provider);
    String loc = lat + "," + lng;

    String messageToSend = null;
    DBConnection dbc = new DBConnection(getBaseContext());
    if (location != null) {
      dbc.addLocation(loc);
    }
    try {
      Bundle extras = intent.getExtras();

      if (extras != null) {
        if (extras.containsKey("numarray") && !extras.containsKey("imageURL")) {
          String[] numarray = extras.getStringArray("numarray");
          Toast.makeText(getBaseContext(), "count" + numarray.length, Toast.LENGTH_SHORT);
          System.out.println(numarray.length);
          try {
            for (int i = 0; i < numarray.length; i++) {
              SmsManager sms = SmsManager.getDefault(); // using android SmsManager
              if (location != null) {
                messageToSend =
                    new String("I'm at " + loc + "\n" + "http://maps.google.com/maps?q=loc:" + loc);
              } else {
                messageToSend = "Alert! I'm in trouble";
              }
              ArrayList<String> msgParts = sms.divideMessage(messageToSend);
              sms.sendMultipartTextMessage(numarray[i], null, msgParts, null, null);
              Toast.makeText(getBaseContext(), "SMS Sent to " + numarray[i], Toast.LENGTH_SHORT)
                  .show();
              isAlertSent = true;
            }

          } catch (Exception e) {
            Toast.makeText(getBaseContext(), "SMS could not be sent", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            isAlertSent = false;
          }
        }

        if (extras.containsKey("numarray") && extras.containsKey("imageURL")) {
          String[] numarray = extras.getStringArray("numarray");
          String url = extras.getString("imageURL");

          try {
            for (int i = 0; i < numarray.length; i++) {
              SmsManager sms = SmsManager.getDefault(); // using android SmsManager
              if (location != null) {
                messageToSend =
                    new String(
                        "I'm at "
                            + loc
                            + "\n"
                            + "http://maps.google.com/maps?q=loc:"
                            + loc
                            + "\nPlease see my image at: "
                            + url);
              } else {
                messageToSend = "Alert! I'm in trouble" + "\nPlease see my image at: " + url;
              }
              ArrayList<String> msgParts = sms.divideMessage(messageToSend);
              sms.sendMultipartTextMessage(numarray[i], null, msgParts, null, null);
              // sms.sendTextMessage(numarray[i], null, "Image: "+url +"    I'm at
              // "+loc+"\n"+"http://maps.google.com/maps?q=loc:"+loc, null, null);  // adding number
              // and text
              Toast.makeText(getBaseContext(), "SMS Sent to " + numarray[i], Toast.LENGTH_SHORT)
                  .show();
              isAlertSent = true;
            }

          } catch (Exception e) {
            Toast.makeText(getBaseContext(), "SMS could not be sent", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            isAlertSent = false;
          }
        }

        if (extras.containsKey("num")) {
          String num = extras.getString("num");
          try {

            SmsManager sms = SmsManager.getDefault(); // using android SmsManager
            List<String> val = dbc.getLocation();
            String prev = null;
            System.out.println(val.size() + val.get(0));
            if (val.size() != 0) {
              prev = val.get(0);
              Log.d("test", prev);
              if (!prev.contains("0.0,0.0")) {
                prevlocation = prev;
              } else {
                prevlocation = null;
              }
              System.out.println(prev);
            } else {
              prevlocation = null;
            }
            if (location != null) {
              messageToSend =
                  new String("I'm at " + loc + "\n" + "http://maps.google.com/maps?q=loc:" + loc);
            } else {
              if (prevlocation != null) {
                messageToSend =
                    "Your device's location service is off"
                        + "\nLast known location is "
                        + prevlocation;
              } else {
                messageToSend =
                    "Your device's location service is off"
                        + "\nNo Last known location data available";
              }
            }
            ArrayList<String> msgParts = sms.divideMessage(messageToSend);
            sms.sendMultipartTextMessage(num, null, msgParts, null, null);
            isAlertSent = true;
            dbc.addAccessTime(num, getDateTime());

          } catch (Exception e) {
            Toast.makeText(getBaseContext(), "SMS could not be sent", Toast.LENGTH_SHORT).show();
            isAlertSent = false;
            e.printStackTrace();
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return START_STICKY;
  }
コード例 #9
0
  public boolean sendMessage(long token) throws MmsException {
    if (LogTag.DEBUG_SEND) {
      Log.v(TAG, "sendMessage token: " + token);
    }
    if (mMessageText == null) {
      // Don't try to send an empty message, and destination should be just
      // one.
      throw new MmsException("Null message body or have multiple destinations.");
    }
    SmsManager smsManager = SmsManager.getDefault();
    ArrayList<String> messages = null;
    if ((MmsConfig.getEmailGateway() != null)
        && (Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) {
      String msgText;
      msgText = mDest + " " + mMessageText;
      mDest = MmsConfig.getEmailGateway();
      messages = smsManager.divideMessage(msgText);
    } else {
      messages = smsManager.divideMessage(mMessageText);
      // remove spaces and dashes from destination number
      // (e.g. "801 555 1212" -> "8015551212")
      // (e.g. "+8211-123-4567" -> "+82111234567")
      mDest = PhoneNumberUtils.stripSeparators(mDest);
      mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest);
    }
    int messageCount = messages.size();

    if (messageCount == 0) {
      // Don't try to send an empty message.
      throw new MmsException(
          "SmsMessageSender.sendMessage: divideMessage returned "
              + "empty messages. Original message is \""
              + mMessageText
              + "\"");
    }

    boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0);
    if (!moved) {
      throw new MmsException(
          "SmsMessageSender.sendMessage: couldn't move message " + "to outbox: " + mUri);
    }
    if (LogTag.DEBUG_SEND) {
      Log.v(
          TAG,
          "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " + mRequestDeliveryReport);
    }

    ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount);
    ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount);
    for (int i = 0; i < messageCount; i++) {
      if (mRequestDeliveryReport && (i == (messageCount - 1))) {
        // TODO: Fix: It should not be necessary to
        // specify the class in this intent.  Doing that
        // unnecessarily limits customizability.
        deliveryIntents.add(
            PendingIntent.getBroadcast(
                mContext,
                0,
                new Intent(
                    MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION,
                    mUri,
                    mContext,
                    MessageStatusReceiver.class),
                0));
      } else {
        deliveryIntents.add(null);
      }
      Intent intent =
          new Intent(SmsReceiverService.MESSAGE_SENT_ACTION, mUri, mContext, SmsReceiver.class);

      int requestCode = 0;
      if (i == messageCount - 1) {
        // Changing the requestCode so that a different pending intent
        // is created for the last fragment with
        // EXTRA_MESSAGE_SENT_SEND_NEXT set to true.
        requestCode = 1;
        intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true);
      }
      if (LogTag.DEBUG_SEND) {
        Log.v(TAG, "sendMessage sendIntent: " + intent);
      }
      sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0));
    }
    try {
      if (MultiSimConfig.isMultiSimEnabled()) {
        MSimSmsManager smsManagerMSim = MSimSmsManager.getDefault();
        smsManagerMSim.sendMultipartTextMessage(
            mDest,
            mServiceCenter,
            messages,
            sentIntents,
            deliveryIntents,
            ComposeMessageActivity.subSelected);
        Log.v(TAG, "뇰랙죄崗엥친駕가가가가!mSubscription: " + mSubscription);

      } else {
        smsManager.sendMultipartTextMessage(
            mDest, mServiceCenter, messages, sentIntents, deliveryIntents);
      }
    } catch (Exception ex) {
      Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex);
      throw new MmsException(
          "SmsMessageSender.sendMessage: caught " + ex + " from MSimSmsManager.sendTextMessage()");
    }
    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
      log(
          "sendMessage: address="
              + mDest
              + ", threadId="
              + mThreadId
              + ", uri="
              + mUri
              + ", msgs.count="
              + messageCount);
    }
    return false;
  }
コード例 #10
0
    @Override
    protected Void doInBackground(Void... arg0) {
      if (isHoneycomb) {
        final ParseQuery query = new ParseQuery(Preferences.PARSE_TABLE_SMS);
        // Sort the Parse Object so only the username of the current
        // user can be accessed.
        query.whereEqualTo(Preferences.PARSE_USERNAME_ROW, Util.getUsernameString());
        // The most recent message added will be on top.
        query.orderByDescending("createdAt");
        // Only need to get one message from the server, each message
        // will be from a push
        query.setLimit(1);
        try {
          List<ParseObject> messageList = query.find();
          for (ParseObject messageObject : messageList) {
            // Open up the database
            // Get the parse object id
            String objectId = messageObject.objectId();
            // with the objectid you can query the server
            ParseObject message = query.get(objectId);
            // Get the time the message was added to the server
            Date time = message.createdAt();
            // Format the time to (Fri Jan 13 12:00)
            SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd hh:mm");
            String formatedTime = sdf.format(time);
            String timeDB = formatedTime.toString();
            String addressDB = message.getString("address");
            String bodyDB = message.getString("body");
            int readDB = message.getInt("read");
            int smsIdDB = message.getInt("smsId");
            String subjectDB = message.getString("subject");
            int threadIdDB = message.getInt("threadId");
            int typeDB = message.getInt("type");
            int onDeviceDB = message.getInt("onDevice");
            String usernameDB = message.getString("username");
            // Display the total message queryed for
            // logging
            String totalMessage =
                "Sent: "
                    + timeDB
                    + "\n"
                    + "Address: "
                    + addressDB
                    + "\n"
                    + "Message : "
                    + bodyDB
                    + "\n";
            Log.d(TAG, "New message is: " + totalMessage);
            // Get the MessageItem object so you can
            // create the db entry.
            MessageItem item =
                new MessageItem(
                    timeDB,
                    addressDB,
                    bodyDB,
                    readDB,
                    smsIdDB,
                    subjectDB,
                    threadIdDB,
                    typeDB,
                    onDeviceDB,
                    usernameDB);
            // Insert the MessageItem into the sms2honeycomb.db.
            dbAdapter.insertMessageItem(item);

            // TODO update the listadapter to display the new
            // message via an intent/ service?

            String intentString = "com.asa.texttotab.UPDATE_LIST";
            Intent updateIntent = new Intent();
            updateIntent.setAction(intentString);
            mContext.sendBroadcast(updateIntent);

            // TODO NOTICIFATIONS
          }
        } catch (ParseException e) {
          // TODO - Handle situation where querying server failed
          dbAdapter.close();
          Log.e(TAG, "querying server failed");
          e.printStackTrace();
        }
      } else {
        Log.e(TAG, "The device is not honeycomb is its a phone.");
        // If the device is not a tablet it is a phone so you pull from
        // the
        // server, but then send a sms message from the data recived.
        // We want to query the sms table
        final ParseQuery query = new ParseQuery(Preferences.PARSE_TABLE_SMS);
        // Sort the Parse Object so only the username of the current
        // user
        // can be accessed.
        query.whereEqualTo(Preferences.PARSE_USERNAME_ROW, Util.getUsernameString());
        // The most recent message added will be on top.
        query.orderByDescending("createdAt");
        // Only need to get one message from the server, each message
        // will be from a push
        query.setLimit(1);
        try {
          List<ParseObject> messageList = query.find();
          // For the ParseObjects quering get all that needs
          // to be done.
          for (ParseObject messageObject : messageList) {
            // Get the parse object id
            String objectId = messageObject.objectId();
            // with the objectid you can query the
            // server
            ParseObject message = query.get(objectId);
            // Get the time the message was created at
            // for
            // logging, do not need a time to send a
            // message.
            Date time = message.createdAt();
            String timeString = time.toString();
            // Get who the message is coming from
            // (phonenumber).
            String address = message.getString(Preferences.PARSE_SMS_ADDRESS);
            // Get the body of the message
            String body = message.getString(Preferences.PARSE_SMS_BODY);
            // Display the total message queryed for
            // logging
            String totalMessage =
                "Sent: " + timeString + "\n" + "To: " + address + "\n" + "Message : " + body + "\n";
            Log.d(TAG, "New message is: " + totalMessage);
            // get the smsmanager as sms
            SmsManager sms = SmsManager.getDefault();
            // If the message is over the 160 Char limit
            // it
            // will be choped up.
            if (body.length() > 160) {
              // Chops up the message
              sms.divideMessage(body);
              // Send the sms message in its parts
              sms.sendMultipartTextMessage(address, null, sms.divideMessage(body), null, null);
            } else {
              // Sends the message without cutting it
              sms.sendTextMessage(address, null, body, null, null);
            }
          }
        } catch (ParseException e) {
          // TODO - Handle situation where querying server failed
          e.printStackTrace();
        }
      }
      return null;
    }
コード例 #11
0
  @Override
  public void send(String aNumber, String aMessage, int aRequestId) {
    int envelopeId = Postman.kUnknownEnvelopeId;

    try {
      SmsManager sm = SmsManager.getDefault();

      Intent sentIntent = new Intent(ACTION_SMS_SENT);
      Intent deliveredIntent = new Intent(ACTION_SMS_DELIVERED);

      Bundle bundle = new Bundle();
      bundle.putString("number", aNumber);
      bundle.putString("message", aMessage);
      bundle.putInt("requestId", aRequestId);

      if (aMessage.length() <= kMaxMessageSize) {
        envelopeId = Postman.getInstance().createEnvelope(1);
        bundle.putInt("envelopeId", envelopeId);

        sentIntent.putExtras(bundle);
        deliveredIntent.putExtras(bundle);

        /*
         * There are a few things to know about getBroadcast and pending intents:
         * - the pending intents are in a shared pool maintained by the system;
         * - each pending intent is identified by a token;
         * - when a new pending intent is created, if it has the same token as
         *   another intent in the pool, one of them has to be removed.
         *
         * To prevent having a hard time because of this situation, we give a
         * unique id to all pending intents we are creating. This unique id is
         * generated by GetPendingIntentUID().
         */
        PendingIntent sentPendingIntent =
            PendingIntent.getBroadcast(
                GeckoAppShell.getContext(),
                PendingIntentUID.generate(),
                sentIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        PendingIntent deliveredPendingIntent =
            PendingIntent.getBroadcast(
                GeckoAppShell.getContext(),
                PendingIntentUID.generate(),
                deliveredIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        sm.sendTextMessage(aNumber, "", aMessage, sentPendingIntent, deliveredPendingIntent);
      } else {
        ArrayList<String> parts = sm.divideMessage(aMessage);
        envelopeId = Postman.getInstance().createEnvelope(parts.size());
        bundle.putInt("envelopeId", envelopeId);

        sentIntent.putExtras(bundle);
        deliveredIntent.putExtras(bundle);

        ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>(parts.size());
        ArrayList<PendingIntent> deliveredPendingIntents =
            new ArrayList<PendingIntent>(parts.size());

        for (int i = 0; i < parts.size(); ++i) {
          sentPendingIntents.add(
              PendingIntent.getBroadcast(
                  GeckoAppShell.getContext(),
                  PendingIntentUID.generate(),
                  sentIntent,
                  PendingIntent.FLAG_CANCEL_CURRENT));

          deliveredPendingIntents.add(
              PendingIntent.getBroadcast(
                  GeckoAppShell.getContext(),
                  PendingIntentUID.generate(),
                  deliveredIntent,
                  PendingIntent.FLAG_CANCEL_CURRENT));
        }

        sm.sendMultipartTextMessage(
            aNumber, "", parts, sentPendingIntents, deliveredPendingIntents);
      }
    } catch (Exception e) {
      Log.e("GeckoSmsManager", "Failed to send an SMS: ", e);

      if (envelopeId != Postman.kUnknownEnvelopeId) {
        Postman.getInstance().destroyEnvelope(envelopeId);
      }

      notifySmsSendFailed(kUnknownError, aRequestId);
    }
  }