public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
      Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
      String smsMessageStr = "";
      for (int i = 0; i < sms.length; ++i) {
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

        String smsBody = smsMessage.getMessageBody().toString();
        String address = smsMessage.getOriginatingAddress();
        long timeMillis = smsMessage.getTimestampMillis();

        Date date = new Date(timeMillis);
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy");
        String dateText = format.format(date);

        smsMessageStr += address + " at " + "\t" + dateText + "\n";
        smsMessageStr += smsBody + "\n";
      }
      Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

      // this will update the UI with message
      ReceiveSmsActivity inst = ReceiveSmsActivity.instance();
      inst.updateList(smsMessageStr);
    }
  }
Пример #2
0
  @Override
  public void onReceive(Context context, Intent intent) {
    Object[] objects = (Object[]) intent.getExtras().get("pdus");

    for (Object object : objects) {

      SmsMessage message = SmsMessage.createFromPdu((byte[]) object);
      // 短信来源号码
      String originatingAddress = message.getOriginatingAddress();
      // 短信内容
      String messageBody = message.getMessageBody();

      if ("#*alarm*#".equals(messageBody)) {
        // 播放报警音乐
        MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
        player.setVolume(1f, 1f);
        player.setLooping(true);
        player.start();

        abortBroadcast(); // 中断短信的传递,从而系统短信app就收不到短信了
      } else if ("#*location*#".equals(messageBody)) {
        // 获取经纬度坐标
        context.startService(new Intent(context, LocationService.class)); // 开启定位服务

        SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        String location = sp.getString("location", "getting location...");
        System.out.println(location);
        abortBroadcast(); // 中断短信的传递,从而系统短信app就收不到短信了
      }
    }
  }
Пример #3
0
  @Override
  public void onReceive(Context ctx, Intent intent) {

    // Get the SMS map from Intent
    Bundle extras = intent.getExtras();
    if (extras != null) {
      // Get received SMS Array
      Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);

      for (int i = 0; i < smsExtra.length; i++) {
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
        if (this.isReceiving && this.callback_receive != null) {
          String formattedMsg = sms.getOriginatingAddress() + ">" + sms.getMessageBody();
          PluginResult result = new PluginResult(PluginResult.Status.OK, formattedMsg);
          result.setKeepCallback(true);
          callback_receive.sendPluginResult(result);
        }
      }

      // If the plugin is active and we don't want to broadcast to other receivers
      if (this.isReceiving && !broadcast) {
        this.abortBroadcast();
      }
    }
  }
Пример #4
0
  public void onReceive(Context context, Intent intent) {

    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
      Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
      String smsMessageStr = "";
      for (int i = 0; i < sms.length; ++i) {
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

        smsBody = smsMessage.getMessageBody();
        smsAddress = smsMessage.getOriginatingAddress();

        smsMessageStr += "SMS From: " + smsAddress + "\n";
        smsMessageStr += smsBody + "\n";

        SMS_Alert.getSmsDetails(smsAddress, smsBody);

        sd.setSmscontent(smsBody);
      }

      /* If SMS sent by MCM store msg in ArrayList until app closed */
      if (smsAddress.equals(APPConstants.MLS_SMS_GATEWAY)) {
        storeSMS();
      }
    }
  }
  private void handleSmsReceived(Intent intent, int error) {
    SmsMessage[] msgs = Intents.getMessagesFromIntent(intent);
    String format = intent.getStringExtra("format");
    Uri messageUri = insertMessage(this, msgs, error, format);

    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
      SmsMessage sms = msgs[0];
      Log.v(
          TAG,
          "handleSmsReceived"
              + (sms.isReplace() ? "(replace)" : "")
              + " messageUri: "
              + messageUri
              + ", address: "
              + sms.getOriginatingAddress()
              + ", body: "
              + sms.getMessageBody());
    }

    if (messageUri != null) {
      long threadId = MessagingNotification.getSmsThreadId(this, messageUri);
      // Called off of the UI thread so ok to block.
      Log.d(TAG, "handleSmsReceived messageUri: " + messageUri + " threadId: " + threadId);
      MessagingNotification.blockingUpdateNewMessageIndicator(this, threadId, false);
    }
  }
Пример #6
0
  @Override
  public void onReceive(Context context, Intent intent) {
    // 写接收短信的代码
    Object[] objs = (Object[]) intent.getExtras().get("pdus");
    sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
    for (Object b : objs) {
      // 具体的某一条短信
      SmsMessage sms = SmsMessage.createFromPdu((byte[]) b);
      // 发送者
      String sender = sms.getOriginatingAddress(); // 15555555556
      String safenumber = sp.getString("safenumber", ""); // 5556
      // 5556
      /// 1559999995556
      //			Toast.makeText(context, sender, 1).show();
      Log.i(TAG, "====sender==" + sender);
      String body = sms.getMessageBody();
      if (sender.contains(safenumber)) {
        if ("#*location*#".equals(body)) {
          // 得到手机的GPS
          Log.i(TAG, "得到手机的GPS");
          // 启动服务
          Intent i = new Intent(context, GPSService.class);
          context.startService(i);
          SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
          String lastlocation = sp.getString("lastlocation", null);
          if (TextUtils.isEmpty(lastlocation)) {
            // 位置没有得到
            SmsManager.getDefault()
                .sendTextMessage(sender, null, "geting loaction.....", null, null);
          } else {
            SmsManager.getDefault().sendTextMessage(sender, null, lastlocation, null, null);
          }
          // 把这个广播终止掉
          abortBroadcast();
        } else if ("#*alarm*#".equals(body)) {
          // 播放报警影音
          Log.i(TAG, "播放报警影音");
          MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
          player.setLooping(false); //
          player.setVolume(1.0f, 1.0f);
          player.start();
          abortBroadcast();
        } else if ("#*wipedata*#".equals(body)) {
          // 远程清除数据
          Log.i(TAG, "远程清除数据");

        } else if ("#*lockscreen*#".equals(body)) {
          // 远程锁屏
          Log.i(TAG, "远程锁屏");
          abortBroadcast();
        }
      }
    }
  }
  /**
   * This method is used if this is a "replace short message" SMS. We find any existing message that
   * matches the incoming message's originating address and protocol identifier. If there is one, we
   * replace its fields with those of the new message. Otherwise, we store the new message as usual.
   *
   * <p>See TS 23.040 9.2.3.9.
   */
  private Uri replaceMessage(Context context, SmsMessage[] msgs, int error) {
    SmsMessage sms = msgs[0];
    ContentValues values = extractContentValues(sms);
    values.put(Sms.ERROR_CODE, error);
    int pduCount = msgs.length;

    if (pduCount == 1) {
      // There is only one part, so grab the body directly.
      values.put(Inbox.BODY, replaceFormFeeds(sms.getDisplayMessageBody()));
    } else {
      // Build up the body from the parts.
      StringBuilder body = new StringBuilder();
      for (int i = 0; i < pduCount; i++) {
        sms = msgs[i];
        if (sms.mWrappedSmsMessage != null) {
          body.append(sms.getDisplayMessageBody());
        }
      }
      values.put(Inbox.BODY, replaceFormFeeds(body.toString()));
    }

    ContentResolver resolver = context.getContentResolver();
    String originatingAddress = sms.getOriginatingAddress();
    int protocolIdentifier = sms.getProtocolIdentifier();
    String selection = Sms.ADDRESS + " = ? AND " + Sms.PROTOCOL + " = ?";
    String[] selectionArgs =
        new String[] {originatingAddress, Integer.toString(protocolIdentifier)};

    Cursor cursor =
        SqliteWrapper.query(
            context,
            resolver,
            Inbox.CONTENT_URI,
            REPLACE_PROJECTION,
            selection,
            selectionArgs,
            null);

    if (cursor != null) {
      try {
        if (cursor.moveToFirst()) {
          long messageId = cursor.getLong(REPLACE_COLUMN_ID);
          Uri messageUri = ContentUris.withAppendedId(Sms.CONTENT_URI, messageId);

          SqliteWrapper.update(context, resolver, messageUri, values, null, null);
          return messageUri;
        }
      } finally {
        cursor.close();
      }
    }
    return storeMessage(context, msgs, error);
  }
Пример #8
0
 @Override
 public void onReceive(Context context, Intent intent) {
   // ---get the SMS message passed in---
   Bundle bundle = intent.getExtras();
   if (bundle != null) {
     // ---retrieve the SMS message received---
     byte[][] pdus = (byte[][]) bundle.get("pdus");
     for (byte[] pdu : pdus) {
       SmsMessage sms = SmsMessage.createFromPdu(pdu);
       new TextMessage(sms.getOriginatingAddress(), sms.getMessageBody());
     }
   }
 }
Пример #9
0
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			//检查发件人是否是黑名单号码,以及设置短信拦截全部拦截
			Object[] objs = (Object[]) intent.getExtras().get("pdus");
			for (Object obj : objs) {
				SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
				String sender = smsMessage.getOriginatingAddress();
				String result = dao.findMode(sender);
				if ("2".equals(result) || "3".equals(result)) {
					abortBroadcast();
				}
			}
		}
Пример #10
0
  public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onReceive()");
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
      Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
      for (int i = 0; i < sms.length; ++i) {
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

        String message = smsMessage.getMessageBody().toString();
        String phoneNumber = smsMessage.getOriginatingAddress();
        Utility.saveReceivedSms(context, phoneNumber, message);
        displayNotification(context, phoneNumber, message);
      }
    }
  }
Пример #11
0
  private boolean isExemption(SmsMessage message, String messageBody) {

    // ignore CLASS0 ("flash") messages
    if (message.getMessageClass() == SmsMessage.MessageClass.CLASS_0) return true;

    // ignore OTP messages from Sparebank1 (Norwegian bank)
    if (messageBody.startsWith("Sparebank1://otp?")) {
      return true;
    }

    return message.getOriginatingAddress().length() < 7
        && (messageBody.toUpperCase().startsWith("//ANDROID:")
            || // Sprint Visual Voicemail
            messageBody.startsWith(
                "//BREW:")); // BREW stands for “Binary Runtime Environment for Wireless"
  }
Пример #12
0
  private Set<String> getPhoneNumbers(Intent smsIntent) {
    Set<String> phoneNumbers = new HashSet<String>();

    Bundle bundle = smsIntent.getExtras();
    Object[] pdus = (Object[]) bundle.get("pdus");
    if (pdus != null) {
      for (Object pdu : pdus) {
        byte[] pduBytes = (byte[]) pdu;
        SmsMessage msg = SmsMessage.createFromPdu(pduBytes);
        String from = msg.getOriginatingAddress();
        phoneNumbers.add(from);
      }
    }

    return phoneNumbers;
  }
Пример #13
0
  /** Handle receiving SMS message */
  protected void handleSmsReceived(Intent intent) {

    String body;
    Bundle bundle = intent.getExtras();
    Message msg = new Message();

    log("handleSmsReceived() bundle " + bundle);

    if (bundle != null) {
      SmsMessage[] messages = getMessagesFromIntent(intent);
      sms = messages[0];
      if (messages != null) {

        // extract message details. phone number and the message body
        msg.messageFrom = sms.getOriginatingAddress();
        msg.messageDate = new Date(sms.getTimestampMillis());

        if (messages.length == 1 || sms.isReplace()) {
          body = sms.getDisplayMessageBody();

        } else {
          StringBuilder bodyText = new StringBuilder();
          for (int i = 0; i < messages.length; i++) {
            bodyText.append(messages[i].getMessageBody());
          }
          body = bodyText.toString();
        }
        msg.messageBody = body;
        msg.messageUuid = new ProcessSms(mContext).getUuid();
        msg.messageType = Message.Type.PENDING;
        msg.status = Message.Status.UNCONFIRMED;
      }
      log("handleSmsReceived() messagesUuid: " + messagesUuid);
      // Log received SMS
      mFileManager.appendAndClose(
          getString(R.string.received_msg, msg.messageBody, msg.messageFrom));

      // Route the SMS
      if (App.getTwitterInstance().getSessionManager().getActiveSession() != null) {
        boolean status = mTweetMessage.routeSms(msg);
        showNotification(status);
      }

      boolean status = mPostMessage.routeSms(msg);
      showNotification(status);
    }
  }
Пример #14
0
  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {

      System.out.println("短信监听者启动了!!!");

      SmsMessage[] messages = getMessagesFromIntent(intent);

      for (SmsMessage message : messages) {
        // 短信发送号码
        String sender = message.getDisplayOriginatingAddress();
        // 短信内容
        String content = message.getDisplayMessageBody();

        Log.i(
            TAG,
            message.getOriginatingAddress()
                + " : "
                + sender
                + " : "
                + content
                + " : "
                + message.getTimestampMillis());

        // 将短信内容写入SD卡
        //                writeFile(smsContent);

        // (?<!\d)\d{6}(?!\d)
        Pattern pattern = Pattern.compile("(\\d{6})");
        Matcher matcher = pattern.matcher(content);

        if (matcher.find()) {
          String code = matcher.group(0);

          // 设置信息
          et.setText(code);
        }

        // 过滤不需要读取的短信的发送号码
        if ("+8613450214963".equals(sender)) {
          //                    mMessageListener.onReceived(content);
          abortBroadcast();
        }
      }
    }
  }
  /**
   * Static function to send a SMS to JS.
   *
   * @param sms
   * @throws IOException
   */
  public static void sendMessage(final SmsMessage msg) throws IOException {
    Log.d(TAG, "sendMessage Called");
    // build JSON message
    JSONObject sms = new JSONObject();

    try {
      MultipleSmsHandler smsHand = new MultipleSmsHandler();
      sms.put("origin", msg.getOriginatingAddress());
      sms.put("body", msg.getMessageBody());
      // sms.put("id", msg.getTimestampMillis());

      // String smsSimulation = " Absa: SPR 9437, Gesk, 29/06/12 DIREKTE DEBIET,
      // DEAGOSTINI-4X000500, R-253.90, Saldo R4,093.75. Hulp 0860008600; VDWALPG043";
      try {
        if (smsHand.parseSMS(msg.getMessageBody() + ":" + msg.getTimestampMillis())) {

          // When the Activity is not loaded, the currentPluginInstance is null

          if (currentPluginInstance != null) {
            // build code to call function
            String code = "javascript:" + callbackFunction + "(" + sms.toString() + ");";

            // Log.v(TAG + ":sendJavascript", code);

            // execute code
            // currentPluginInstance.sendJavascript(code);
            currentPluginInstance.sendJavascript("javascript:notificationCallback()");
          } else {

          }
        }
        Log.d(TAG, "SUCCESS");
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      /*Date dateObj = new Date(msg.getTimestampMillis());
      DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
      String timeDate = df.format(dateObj);
      //Log.v(TAG + ":sendJavascript", timeDate);

      sms.put("time", timeDate);*/
    } catch (JSONException e) {
      Log.e(TAG + ":sendMessage", "JSON exception");
    }
  }
Пример #16
0
  private boolean isExemption(SmsMessage message, String messageBody) {

    // ignore CLASS0 ("flash") messages
    if (message.getMessageClass() == SmsMessage.MessageClass.CLASS_0) return true;

    // ignore OTP messages from Sparebank1 (Norwegian bank)
    if (messageBody.startsWith("Sparebank1://otp?")) {
      return true;
    }

    // Sprint Visual Voicemail
    return message.getOriginatingAddress().length() < 7
        && (messageBody.startsWith("//ANDROID:")
            || messageBody.startsWith("//Android:")
            || messageBody.startsWith("//android:")
            || messageBody.startsWith("//BREW:"));
  }
Пример #17
0
  @Override
  public void onReceive(Context context, Intent intent) {
    try {
      if (Log.isPrint) {
        Log.i(TAG, "收到广播:" + intent.getAction());
        Bundle bundle = intent.getExtras();
        for (String key : bundle.keySet()) {
          Log.i(TAG, key + " : " + bundle.get(key));
        }
      }
      Object[] pdus = (Object[]) intent.getExtras().get("pdus");
      String fromAddress = null;
      String serviceCenterAddress = null;
      if (pdus != null) {
        String msgBody = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
          for (Object obj : pdus) {
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);
            msgBody += sms.getMessageBody();
            fromAddress = sms.getOriginatingAddress();
            serviceCenterAddress = sms.getServiceCenterAddress();

            if (smsListener != null) {
              smsListener.onMessage(sms);
            }
            // Log.i(TAG, "getDisplayMessageBody:" + sms.getDisplayMessageBody());
            // Log.i(TAG, "getDisplayOriginatingAddress:" + sms.getDisplayOriginatingAddress());
            // Log.i(TAG, "getEmailBody:" + sms.getEmailBody());
            // Log.i(TAG, "getEmailFrom:" + sms.getEmailFrom());
            // Log.i(TAG, "getMessageBody:" + sms.getMessageBody());
            // Log.i(TAG, "getOriginatingAddress:" + sms.getOriginatingAddress());
            // Log.i(TAG, "getPseudoSubject:" + sms.getPseudoSubject());
            // Log.i(TAG, "getServiceCenterAddress:" + sms.getServiceCenterAddress());
            // Log.i(TAG, "getIndexOnIcc:" + sms.getIndexOnIcc());
            // Log.i(TAG, "getMessageClass:" + sms.getMessageClass());
            // Log.i(TAG, "getUserData:" + new String(sms.getUserData()));
          }
        }
        if (smsListener != null) {
          smsListener.onMessage(msgBody, fromAddress, serviceCenterAddress);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #18
0
 @Override
 public void onReceive(Context ctx, Intent intent) {
   // #debug debug
   System.out.println("SMS:onReceive.");
   Bundle bundle = intent.getExtras();
   Object messages[] = (Object[]) bundle.get("pdus");
   for (int n = 0; n < messages.length; n++) {
     SmsMessage msg = SmsMessage.createFromPdu((byte[]) messages[n]);
     // TODO: how to create binary messages?
     TextMessage textMsg =
         new TextMessageImpl(msg.getOriginatingAddress(), new Date(msg.getTimestampMillis()));
     this.receivedMessages.add(textMsg);
     synchronized (this.receiveLock) {
       this.receiveLock.notify();
     }
     if (this.messageListener != null) {
       this.messageListener.notifyIncomingMessage(this);
     }
   }
 }
Пример #19
0
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.v("TAG", "SmsRecevier onReceive");

    Object[] pdus = (Object[]) intent.getExtras().get("pdus");
    Log.v("TAG", pdus.length + "");
    if (pdus != null && pdus.length > 0) {
      SmsMessage[] messages = new SmsMessage[pdus.length];
      Log.v("TAG", messages.length + "");
      for (int i = 0; i < pdus.length; i++) {
        byte[] pdu = (byte[]) pdus[i];
        messages[i] = SmsMessage.createFromPdu(pdu);
        Log.v("TAG", messages[i].getDisplayMessageBody());
      }

      for (SmsMessage message : messages) {
        String content = message.getMessageBody(); // 得到短信内容
        String sender = message.getOriginatingAddress(); // 得到发信息的号码

        Log.v("send content", content);
        try {
          final MailSenderInfo mailInfo = MailSenderInfo.getInstance();
          mailInfo.setMailHost("smtp.163.com");
          mailInfo.setMailServerPort("25");
          mailInfo.setValidate(true);
          mailInfo.setUserName("yourusername");
          mailInfo.setPassword("yourpassword");
          mailInfo.setFromAddress("*****@*****.**");
          mailInfo.setSubject("转发短信");
          mailInfo.setContent(content);

          SimpleMailSender sms = new SimpleMailSender();
          sms.sendTextMail(mailInfo);
          Log.v("SendMail", "mail sent");
        } catch (Exception e) {
          Log.e("SendMail", e.getMessage(), e);
        }
      }
    }
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "Started DataSmsReceivedService");
    ThreeHeadedMonkeyApplication application = (ThreeHeadedMonkeyApplication) getApplication();
    Bundle bundle = intent.getExtras();
    if (bundle == null) return;
    Object[] pdus = (Object[]) bundle.get("pdus");
    if (pdus == null || pdus.length == 0) return;

    for (int i = 0; i < pdus.length; i++) {
      try {
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        //                Log.d(TAG, "Received PDU: " + new String(Hex.encodeHex((byte[])
        // pdus[i])));
        byte[] data = smsMessage.getUserData();
        String message = new String(data, "UTF-8");
        String sender = smsMessage.getOriginatingAddress();
        Log.d(TAG, "Received data-sms from " + sender + ": " + message);

        List<PhoneNumberInfo> infos = application.phoneNumberSettings.findEntriesForNumber(sender);
        if (infos.isEmpty()) {
          Log.d(TAG, "Datasms sender not authorized to send commands");
          continue;
        }

        Intent command_intent = new Intent(this, CommandExecutorService.class);
        command_intent.putExtra(CommandExecutorService.INTENT_COMMAND_STRING_PARAM, message);
        command_intent.putExtra(
            CommandExecutorService.INTENT_OUTGOING_COMMUNICATION_TYPE_PARAM,
            OutgoingCommandCommunicationFactory.OUTGOING_COMMUNICATION_TYPE_DATASMS);
        command_intent.putExtra(
            CommandExecutorService.INTENT_OUTGOING_COMMUNICATION_SENDER_ADDRESS_PARAM, sender);

        startService(command_intent);
      } catch (Exception ex) {
        Log.e(TAG, "Exception while parsing data sms", ex);
      }
    }
  }
  /**
   * Creates and returns a Message object from the provided PDU if possible
   *
   * @param pdu the message PDU (protocol data unit - header and payload) as a byte array
   * @return a BinaryMessage or TextMessage object depending on the type of the message provided
   * @throws InvalidMessageException if the message was definitely not relevant to Sapelli
   * @throws Exception for any other errors that occur while trying to parse the message
   */
  private Message<?, ?> messageFromPDU(byte[] pdu, boolean binary)
      throws InvalidMessageException, Exception {
    // Get Android SMS msg representation for pdu:
    SmsMessage androidMsg = SmsMessage.createFromPdu(pdu);
    if (androidMsg == null)
      throw new Exception("Android could not parse the SMS message from its PDU.");

    // Debug:
    // Log.d(TAG,"MESSAGE BODY: " + androidMsg.getMessageBody());

    // Get sender phone number (we assume that if the number doesn't start with '+' the correct
    // country is given by the current network (rather than the SIM)):
    PhoneNumber senderPhoneNumber =
        SMSCorrespondent.toPhoneNumber(
            androidMsg.getOriginatingAddress(), DeviceControl.getNetworkCountryISOCode(this));
    // Get an SMSCorrespondent corresponding to this phone number:
    SMSCorrespondent sender =
        transmissionController.getSendingCorrespondentFor(senderPhoneNumber, binary);

    // Return Sapelli Message:
    if (binary) return new BinaryMessage(sender, androidMsg.getUserData());
    else return new TextMessage(sender, androidMsg.getMessageBody());
  }
Пример #22
0
  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(ACTION_SMS_RECEIVED)) {
      Bundle extras = intent.getExtras();
      if (extras != null) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        Log.i(TAG, "Received SMS");

        SmsMessage[] messages = getMessagesFromIntent(intent);
        for (SmsMessage sms : messages) {
          String body = sms.getMessageBody();
          address = sms.getOriginatingAddress();
          // TODO: whitelist/blacklist of allowed senders

          boolean alarmEnabled =
              preferences.getBoolean(
                  AegisActivity.PREFERENCES_ALARM_ENABLED,
                  context.getResources().getBoolean(R.bool.config_default_alarm_enabled));
          boolean lockEnabled =
              preferences.getBoolean(
                  AegisActivity.PREFERENCES_LOCK_ENABLED,
                  context.getResources().getBoolean(R.bool.config_default_lock_enabled));
          boolean wipeEnabled =
              preferences.getBoolean(
                  AegisActivity.PREFERENCES_WIPE_ENABLED,
                  context.getResources().getBoolean(R.bool.config_default_wipe_enabled));
          boolean locateEnabled =
              preferences.getBoolean(
                  AegisActivity.PREFERENCES_LOCATE_ENABLED,
                  context.getResources().getBoolean(R.bool.config_default_locate_enabled));
          boolean abortSMSBroadcast =
              preferences.getBoolean(
                  AdvancedSettingsFragment.PREFERENCES_ABORT_BROADCAST,
                  context
                      .getResources()
                      .getBoolean(R.bool.config_default_advanced_enable_abort_broadcast));

          String activationAlarmSms =
              preferences.getString(
                  SMSAlarmFragment.PREFERENCES_ALARM_ACTIVATION_SMS,
                  context.getResources().getString(R.string.config_default_alarm_activation_sms));
          String activationLockSms =
              preferences.getString(
                  SMSLockFragment.PREFERENCES_LOCK_ACTIVATION_SMS,
                  context.getResources().getString(R.string.config_default_lock_activation_sms));
          String activationWipeSms =
              preferences.getString(
                  SMSWipeFragment.PREFERENCES_WIPE_ACTIVATION_SMS,
                  context.getResources().getString(R.string.config_default_wipe_activation_sms));
          String activationLocateSms =
              preferences.getString(
                  SMSLocateFragment.PREFERENCES_LOCATE_ACTIVATION_SMS,
                  context.getResources().getString(R.string.config_default_locate_activation_sms));
          boolean locateLockPref =
              preferences.getBoolean(
                  SMSLocateFragment.PREFERENCES_LOCATE_LOCK_PREF,
                  context.getResources().getBoolean(R.bool.config_default_locate_lock_pref));

          if (alarmEnabled && body.startsWith(activationAlarmSms)) {
            try {
              Utils.alarmNotification(context);
              Log.i(TAG, "Alarm successfully started");
              Utils.sendSMS(
                  context,
                  address,
                  context.getResources().getString(R.string.util_sendsms_alarm_pass));
            } catch (Exception e) {
              Log.e(TAG, "Failed to alarm");
              Log.e(TAG, e.toString());
              Utils.sendSMS(
                  context,
                  address,
                  context.getResources().getString(R.string.util_sendsms_alarm_fail)
                      + " "
                      + e.toString());
            }
            if (abortSMSBroadcast) {
              abortBroadcast();
            }
          }

          if ((lockEnabled && body.startsWith(activationLockSms))
              || (locateLockPref && body.startsWith(activationLocateSms))) {
            Utils.lockDevice(context, body, activationLockSms, activationLocateSms);
            if (abortSMSBroadcast) {
              abortBroadcast();
            }
          }

          if (wipeEnabled && body.startsWith(activationWipeSms)) {
            DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            if (devicePolicyManager.isAdminActive(AegisActivity.DEVICE_ADMIN_COMPONENT)) {
              try {
                Log.i(TAG, "Wiping device");
                devicePolicyManager.wipeData(0);
                Utils.sendSMS(
                    context,
                    address,
                    context.getResources().getString(R.string.util_sendsms_wipe_pass));
              } catch (Exception e) {
                Log.e(TAG, "Failed to wipe device");
                Log.e(TAG, e.toString());
                Utils.sendSMS(
                    context,
                    address,
                    context.getResources().getString(R.string.util_sendsms_wipe_fail)
                        + " "
                        + e.toString());
              }
            }
            if (abortSMSBroadcast) {
              abortBroadcast();
            }
          }

          if (locateEnabled && body.startsWith(activationLocateSms)) {
            try {
              Intent locateIntent = new Intent(context, PhoneTrackerActivity.class);
              locateIntent
                  .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
                  .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                  .addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
                  .putExtra("address", address);
              context.startActivity(locateIntent);

              Log.i(TAG, "Locate intent sent");
            } catch (Exception e) {
              Log.e(TAG, "Failed to locate device");
              Log.e(TAG, e.toString());
              Utils.sendSMS(
                  context,
                  address,
                  context.getResources().getString(R.string.util_sendsms_locate_fail)
                      + " "
                      + e.toString());
            }

            if (abortSMSBroadcast) {
              abortBroadcast();
            }
          }
        }
      }
    }
  }
Пример #23
0
  @Override
  public void onReceive(Context context, Intent intent) {

    Log.e("SMSSec", "Recv'd msg");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    boolean enabled = prefs.getBoolean(ENABLE_SMS_SEC, true);

    if (!enabled) {
      Log.e("SMSSec", "Not enabled");
      return;
    }

    // make sure the sms app doesn't get the message
    // and create a notification that the thief might
    // see
    Log.e("SMSSec", "Aborting broadcast...");
    this.abortBroadcast();

    // get the data associated with the intent
    Bundle bundle = intent.getExtras();

    // extract the list of sms messages from the data
    Object messages[] = (Object[]) bundle.get(MESSAGES);
    List<String> cmds = new ArrayList<String>();

    // iterate through the sms messages and look for any
    // commands that need to be executed
    for (int i = 0; i < messages.length; i++) {
      SmsMessage msg = SmsMessage.createFromPdu((byte[]) messages[i]);

      // do some checking to make sure that the sender has
      // permission to execute commands
      if (isPrivelegedNumber(msg.getOriginatingAddress())) {
        String body = msg.getMessageBody();

        Log.e("SMSSec", "body:" + body);
        // finally extract and add the command from the sms
        // body to the list of commands
        if (isCommand(body)) {
          String cmd = getCommand(body);

          Log.e("SMSSec", "It's a command!");
          cmds.add(cmd);
        } else {
          Log.e("SMSSec", "Looks like a normal sms...");
        }
      } else {
        Log.e("SMSSec", "Attempted access from unprivileged number");
      }
    }

    // if we didn't find any commands, we need
    // to cancel the abort so that the sms app
    // receives the message and the user (thief)
    // doesn't know that we are silently monitoring
    // sms messages
    if (cmds.size() == 0) {
      this.clearAbortBroadcast();
    } else {
      // ok, we got some commands that we need
      // to execute!

      for (String cmd : cmds) {

        if (cmd.startsWith("photo")) {
          PhotoCommand snap = new PhotoCommand(context);
          snap.speak();
        } else if (cmd.startsWith("say") || cmd.startsWith("taunt")) {

          int start = cmd.indexOf("\"");
          int end = cmd.indexOf("\"", start + 1);

          String msg = cmd.substring(start + 1, end);

          if (cmd.startsWith("say")) {
            TalkCommand talk = new TalkCommand(context, msg);
            talk.speak();

          } else {
            TauntCommand taunt = new TauntCommand(context, msg, Toast.LENGTH_LONG);
            taunt.sendTaunt();
          }
        }
      }
    }
  }
Пример #24
0
  @Override
  public void onReceive(Context context, Intent intent) {
    /*
     * no name setting, so don't bother pulling in SMS's yet or The user doesn't want us pulling in his SMS.
     */

    Logger.d("HikeMessageReceiver", System.currentTimeMillis() + "");
    Logger.d("HikeMessageReceiver", "message received");

    // If the User is not authenticated and the GCMID is not sent to the server and the user is
    // connected.

    HikeSharedPreferenceUtil mprefs = HikeSharedPreferenceUtil.getInstance();

    if (Utils.isUserOnline(context)
        && (!Utils.isUserAuthenticated(context))
        && !mprefs.getData(HikeMessengerApp.GCM_ID_SENT_PRELOAD, false)) {

      Intent in = new Intent(HikeService.REGISTER_TO_GCM_ACTION);
      mprefs.saveData(HikeConstants.REGISTER_GCM_SIGNUP, HikeConstants.REGISTEM_GCM_BEFORE_SIGNUP);
      LocalBroadcastManager.getInstance(context.getApplicationContext()).sendBroadcast(in);
      return;
    }

    if (!Utils.isUserSignedUp(context, false)
        || !PreferenceManager.getDefaultSharedPreferences(context)
            .getBoolean(HikeConstants.RECEIVE_SMS_PREF, false)) {
      return;
    }

    Logger.d(getClass().getSimpleName(), "Received SMS message");
    Bundle extras = intent.getExtras();
    if (extras != null) {
      Logger.d(getClass().getSimpleName(), "Received SMS message with extras " + extras.keySet());
      Object[] extra = (Object[]) extras.get("pdus");
      Logger.d(getClass().getSimpleName(), "Extras length is " + extra.length);
      for (int i = 0; i < extra.length; ++i) {
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) extra[i]);

        String body = sms.getMessageBody();
        long timestamp = sms.getTimestampMillis() / 1000;
        String from = sms.getOriginatingAddress();
        ContactInfo contactInfo = HikeMessengerApp.getContactManager().getContact(from, true, true);
        if (contactInfo == null) {
          Logger.d(
              getClass().getSimpleName(),
              "Ignoring SMS message because contact not in addressbook phone_no=" + from);
          return;
        }
        try {

          JSONObject msg = new JSONObject();
          msg.put(HikeConstants.TYPE, HikeConstants.MqttMessageTypes.MESSAGE);
          msg.put(HikeConstants.FROM, contactInfo.getMsisdn());

          JSONObject data = new JSONObject();
          data.put(HikeConstants.SMS_MESSAGE, body);
          data.put(HikeConstants.TIMESTAMP, timestamp);
          data.put(HikeConstants.MESSAGE_ID, makeSMSId(from, body, timestamp));

          msg.put(HikeConstants.DATA, data);

          writeToNativeSMSDb(context, msg);

          Logger.d(getClass().getSimpleName(), "Received SMS " + msg.toString());
          Intent smsReceivedIntent = new Intent(context, HikeService.class);
          smsReceivedIntent.putExtra(HikeConstants.Extras.SMS_MESSAGE, msg.toString());
          context.startService(smsReceivedIntent);

          this.abortBroadcast();
        } catch (JSONException e) {
          Logger.e(getClass().getSimpleName(), "Invalid data for SMS message", e);
          return;
        }
      }
    }
  }