List of usage examples for android.telephony SmsMessage createFromPdu
@Deprecated public static SmsMessage createFromPdu(byte[] pdu)
From source file:at.flack.receiver.SmsReceiver.java
@Override public void onReceive(Context context, Intent intent) { sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); notify = sharedPrefs.getBoolean("notifications", true); vibrate = sharedPrefs.getBoolean("vibration", true); headsup = sharedPrefs.getBoolean("headsup", true); led_color = sharedPrefs.getInt("notification_light", -16776961); boolean all = sharedPrefs.getBoolean("all_sms", true); if (notify == false) return;//w w w. ja v a 2 s . co m Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); str += msgs[i].getMessageBody().toString(); str += "\n"; } NotificationCompat.Builder mBuilder; if (main != null) { main.addNewMessage(str); return; } boolean use_profile_picture = false; Bitmap profile_picture = null; String origin_name = null; try { origin_name = getContactName(context, msgs[0].getDisplayOriginatingAddress()); if (origin_name == null) origin_name = msgs[0].getDisplayOriginatingAddress(); } catch (Exception e) { } if (origin_name == null) origin_name = "Unknown"; try { profile_picture = RoundedImageView.getCroppedBitmap(Bitmap.createScaledBitmap( fetchThumbnail(context, msgs[0].getDisplayOriginatingAddress()), 200, 200, false), 300); use_profile_picture = true; } catch (Exception e) { use_profile_picture = false; } Resources res = context.getResources(); int positionOfBase64End = str.lastIndexOf("="); if (positionOfBase64End > 0 && Base64.isBase64(str.substring(0, positionOfBase64End))) { mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.raven_notification_icon) .setContentTitle(origin_name).setColor(0xFFB71C1C) .setContentText(res.getString(R.string.sms_receiver_new_encrypted)).setAutoCancel(true); if (use_profile_picture && profile_picture != null) { mBuilder = mBuilder.setLargeIcon(profile_picture); } else { mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name, context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200)); } } else if (str.toString().charAt(0) == '%' && (str.toString().length() == 10 || str.toString().length() == 9)) { int lastIndex = str.toString().lastIndexOf("="); if (lastIndex > 0 && Base64.isBase64(str.toString().substring(1, lastIndex))) { mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name) .setColor(0xFFB71C1C) .setContentText(res.getString(R.string.sms_receiver_handshake_received)) .setSmallIcon(R.drawable.raven_notification_icon).setAutoCancel(true); if (use_profile_picture && profile_picture != null) { mBuilder = mBuilder.setLargeIcon(profile_picture); } else { mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name, context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200)); } } else { return; } } else if (str.toString().charAt(0) == '%' && str.toString().length() >= 120 && str.toString().length() < 125) { // DH Handshake int lastIndex = str.toString().lastIndexOf("="); if (lastIndex > 0 && Base64.isBase64(str.toString().substring(1, lastIndex))) { mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name) .setColor(0xFFB71C1C) .setContentText(res.getString(R.string.sms_receiver_handshake_received)) .setSmallIcon(R.drawable.raven_notification_icon).setAutoCancel(true); if (use_profile_picture && profile_picture != null) { mBuilder = mBuilder.setLargeIcon(profile_picture); } else { mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name, context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200)); } } else { return; } } else { // unencrypted messages if (all) { mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name) .setColor(0xFFB71C1C).setContentText(str).setAutoCancel(true) .setStyle(new NotificationCompat.BigTextStyle().bigText(str)) .setSmallIcon(R.drawable.raven_notification_icon); if (use_profile_picture && profile_picture != null) { mBuilder = mBuilder.setLargeIcon(profile_picture); } else { mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name, context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200)); } } else { return; } } Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); mBuilder.setSound(alarmSound); mBuilder.setLights(led_color, 750, 4000); if (vibrate) { mBuilder.setVibrate(new long[] { 0, 100, 200, 300 }); } Intent resultIntent = new Intent(context, MainActivity.class); resultIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); resultIntent.putExtra("CONTACT_NUMBER", msgs[0].getOriginatingAddress()); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addParentStack(MainActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); if (Build.VERSION.SDK_INT >= 16 && headsup) mBuilder.setPriority(Notification.PRIORITY_HIGH); if (Build.VERSION.SDK_INT >= 21) mBuilder.setCategory(Notification.CATEGORY_MESSAGE); final NotificationManager mNotificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED") && !MainActivity.isOnTop) mNotificationManager.notify(7, mBuilder.build()); // Save SMS if default app if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && Telephony.Sms.getDefaultSmsPackage(context).equals(context.getPackageName())) { ContentValues values = new ContentValues(); values.put("address", msgs[0].getDisplayOriginatingAddress()); values.put("body", str.replace("\n", "").replace("\r", "")); if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) context.getContentResolver().insert(Telephony.Sms.Inbox.CONTENT_URI, values); } } }
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 w ww . j ava 2 s. c om*/ 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:me.myatminsoe.myansms.SmsReceiver.java
static void handleOnReceive(final BroadcastReceiver receiver, final Context context, final Intent intent) { final String action = intent.getAction(); final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakelock.acquire();/*from www . j av a2 s. c om*/ try { Thread.sleep(SLEEP); } catch (InterruptedException e) { e.printStackTrace(); } String t = null; if (SenderActivity.MESSAGE_SENT_ACTION.equals(action)) { handleSent(context, intent, receiver.getResultCode()); } else { boolean silent = false; if (ACTION_SMS_OLD.equals(action) || ACTION_SMS_NEW.equals(action)) { Bundle b = intent.getExtras(); assert b != null; Object[] messages = (Object[]) b.get("pdus"); SmsMessage[] smsMessage = new SmsMessage[messages.length]; int l = messages.length; for (int i = 0; i < l; i++) { smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]); } t = null; if (l > 0) { // concatenate multipart SMS body StringBuilder sbt = new StringBuilder(); for (int i = 0; i < l; i++) { sbt.append(smsMessage[i].getMessageBody()); } t = sbt.toString(); // ! Check in blacklist db - filter spam String s = smsMessage[0].getDisplayOriginatingAddress(); // this code is used to strip a forwarding agent and display the orginated number as sender final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(PreferencesActivity.PREFS_FORWARD_SMS_CLEAN, false) && t.contains(":")) { Pattern smsPattern = Pattern.compile("([0-9a-zA-Z+]+):"); Matcher m = smsPattern.matcher(t); if (m.find()) { s = m.group(1); // now strip the sender from the message Pattern textPattern = Pattern.compile("^[0-9a-zA-Z+]+: (.*)"); Matcher m2 = textPattern.matcher(t); if (t.contains(":") && m2.find()) { t = m2.group(1); Log.d(TAG, "stripped the message"); } } } final SpamDB db = new SpamDB(context); db.open(); if (db.isInDB(smsMessage[0].getOriginatingAddress())) { silent = true; } db.close(); if (action.equals(ACTION_SMS_NEW)) { // API19+: save message to the database ContentValues values = new ContentValues(); values.put("address", s); values.put("body", t); context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values); } } } else if (ACTION_MMS_OLD.equals(action) || ACTION_MMS_MEW.equals(action)) { t = MMS_BODY; // TODO API19+ MMS code } if (!silent) { int count = MAX_SPINS; do { try { Thread.sleep(SLEEP); } catch (InterruptedException e) { e.printStackTrace(); } --count; } while (updateNewMessageNotification(context, t) <= 0 && count > 0); if (count == 0) { // use messages as they are available updateNewMessageNotification(context, null); } } } wakelock.release(); Log.i(TAG, "wakelock released"); }
From source file:com.polyvi.xface.extension.XMessagingExt.java
private void genMsgReceiveBroadcastReceive() { if (null == mMsgReceiveBroadcaseReveiver) { mMsgReceiveBroadcaseReveiver = new BroadcastReceiver() { @Override// w ww.j ava 2 s.c om public void onReceive(Context context, Intent intent) { if (INTENT_ACTION.equals(intent.getAction())) { Bundle bundle = intent.getExtras(); if (null != bundle) { // pdus?? Object[] pdus = (Object[]) bundle.get("pdus"); // SmsMessage[] msgs = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { // ???pdu?,? msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } JSONArray receivedMsgs = buildSmsList(msgs); XEvent evt = XEvent.createEvent(XEventType.MSG_RECEIVED, receivedMsgs.toString()); XSystemEventCenter.getInstance().sendEventAsync(evt); } } } }; } }
From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java
private void genMsgReceiveBroadcastReceiver() { if (null == mMsgReceiveBroadcaseReceiver) { mMsgReceiveBroadcaseReceiver = new BroadcastReceiver() { @Override//ww w . j a v a2s . com public void onReceive(Context context, Intent intent) { if (INTENT_ACTION.equals(intent.getAction())) { Bundle bundle = intent.getExtras(); if (null != bundle) { // pdus?? Object[] pdus = (Object[]) bundle.get("pdus"); // SmsMessage[] msgs = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { // ???pdu?,? msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } JSONArray receivedMsgs = buildSmsList(msgs); XEvent evt = XEvent.createEvent(XEventType.MSG_RECEIVED, receivedMsgs.toString()); ((XFaceMainActivity) mContext).getEventCenter().sendEventAsync(evt); } } } }; } }
From source file:com.money.manager.ex.notifications.SmsReceiverTransactions.java
@Override public void onReceive(Context context, Intent intent) { mContext = context.getApplicationContext(); final BehaviourSettings behav_settings = new BehaviourSettings(mContext); final GeneralSettings gen_settings = new GeneralSettings(mContext); final AppSettings app_settings = new AppSettings(mContext); final PreferenceConstants prf_const = new PreferenceConstants(); //App Settings int baseCurencyID, fromCurrencyID, toCurrencyID; int baseAccountID, fromAccountID, toAccountID; String baseCurrencySymbl, fromAccCurrencySymbl, toAccCurrencySymbl; String baseAccountName, fromAccountName, toAccountName; Boolean autoTransactionStatus = false; Boolean skipSaveTrans = false; try {/*from w ww.ja v a 2 s .c o m*/ //------- if settings enabled the parse the sms and create trans --------------- if (behav_settings.getBankSmsTrans() == true) { //---get the SMS message passed in--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String msgBody = ""; String msgSender = ""; if (bundle != null) { //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); msgSender = msgs[i].getOriginatingAddress(); msgBody += msgs[i].getMessageBody().toString(); } //msgSender = "AT-SIBSMS"; if (isTransactionSms(msgSender)) { // Transaction Sms sender will have format like this AT-SIBSMS, // Promotional sms will have sender like AT-012345 // Not sure how this format will be in out side of India. May I need to update if i get sample ITransactionEntity model = AccountTransaction.create(); mCommon = new EditTransactionCommonFunctions(null, model, database); // find out the trans type using reg ex String[] key_credit_search = { "(credited)", "(received)", "(added)", "(reloaded)", "(deposited)", "(refunded)", "(debited)(.*?)(towards)(\\s)", "(\\s)(received)(.*?)(in(\\s)your)(\\s)", "(sent)(.*?)(to)(\\s)", "(debited)(.*?)(to)(\\s)", "(credited)(.*?)(in)(\\s)", "(credited)(.*?)(to)(\\s)" }; String[] key_debit_search = { "(made)", "(debited)", "(using)", "(paid)", "(purchase)", "(withdrawn)", "(credited)(.*?)(from)(\\s)", "(sent)(.*?)(from)(\\s)", "(\\s)(received)(.*?)(from)(\\s)" }; String transType = ""; Boolean isDeposit = validateTransType(key_credit_search, msgBody.toLowerCase()); Boolean isWithdrawal = validateTransType(key_debit_search, msgBody.toLowerCase()); if (isDeposit == true) { if (isWithdrawal == true) { transType = "Transfer"; String[] transCategory = getCategoryOrSubCategoryByName("Transfer"); if (!transCategory[0].isEmpty()) { mCommon.transactionEntity.setCategoryId(parseInt(transCategory[0])); } if (!transCategory[1].isEmpty()) { mCommon.transactionEntity.setSubcategoryId(parseInt(transCategory[1])); } mCommon.transactionEntity.setTransactionType(TransactionTypes.Transfer); } else { transType = "Deposit"; String[] incomeCategory = getCategoryOrSubCategoryByName("Income"); if (!incomeCategory[0].isEmpty()) { mCommon.transactionEntity.setCategoryId(parseInt(incomeCategory[0])); } if (!incomeCategory[1].isEmpty()) { mCommon.transactionEntity.setSubcategoryId(parseInt(incomeCategory[1])); } mCommon.transactionEntity.setTransactionType(TransactionTypes.Deposit); } } else if (isWithdrawal == true) { transType = "Withdrawal"; mCommon.transactionEntity.setTransactionType(TransactionTypes.Withdrawal); } mCommon.transactionEntity.setStatus(""); mCommon.payeeName = ""; if (transType != "" && msgBody.toLowerCase().contains("otp") == false) { // if not from blank, then nothing to do with sms //Create the intent thatll fire when the user taps the notification// Intent t_intent = new Intent(mContext, CheckingTransactionEditActivity.class); // Db setup MmxHelper = new MmxOpenHelper(mContext, app_settings.getDatabaseSettings().getDatabasePath()); db = MmxHelper.getReadableDatabase(); baseCurencyID = gen_settings.getBaseCurrencytId(); baseAccountID = gen_settings.getDefaultAccountId(); baseAccountName = ""; fromAccountID = -1; fromCurrencyID = -1; fromAccountName = ""; //if default account id selected if (baseAccountID > 0) { fromAccountID = baseAccountID; fromAccountName = baseAccountName; fromCurrencyID = baseCurencyID; } //Get the base currency sysmbl baseCurrencySymbl = getCurrencySymbl(baseCurencyID); fromAccCurrencySymbl = baseCurrencySymbl; //get te from acount details extractAccountDetails(msgBody, transType); if (!fromAccountDetails[0].isEmpty()) { fromAccountID = parseInt(fromAccountDetails[0]); fromAccountName = fromAccountDetails[1]; fromCurrencyID = parseInt(fromAccountDetails[2]); fromAccCurrencySymbl = fromAccountDetails[3]; mCommon.transactionEntity.setAccountId(fromAccountID); } mCommon.transactionEntity.setNotes(msgBody); mCommon.transactionEntity.setDate(new MmxDate().toDate()); //get the trans amount String transAmount = extractTransAmount(msgBody, fromAccCurrencySymbl); String[] transPayee = extractTransPayee(msgBody); //If there is no account no. or payee in the msg & no amt, then this is not valid sms to do transaction if ((!fromAccountDetails[6].isEmpty() || !toAccountDetails[6].isEmpty() || !transPayee[0].isEmpty()) && !transAmount.isEmpty()) { mCommon.transactionEntity.setAmount(MoneyFactory.fromString(transAmount)); String transRefNo = extractTransRefNo(msgBody); //set the ref no. if exists if (!transRefNo.isEmpty()) { mCommon.transactionEntity.setTransactionNumber(transRefNo); } int txnId = getTxnId(transRefNo.trim(), mCommon.transactionEntity.getDateString()); switch (txnId) { case 0: //add new trnsaction if (transType == "Transfer") //if it is transfer { if (!toAccountDetails[0].isEmpty()) // if id exists then considering as account transfer { toAccountID = parseInt(toAccountDetails[0]); toAccountName = toAccountDetails[1]; toCurrencyID = parseInt(toAccountDetails[2]); toAccCurrencySymbl = toAccountDetails[3]; mCommon.transactionEntity.setAccountToId(toAccountID); //convert the to amount from the both currency details CurrencyService currencyService = new CurrencyService(mContext); mCommon.transactionEntity .setAmountTo(currencyService.doCurrencyExchange(fromCurrencyID, mCommon.transactionEntity.getAmount(), toCurrencyID)); mCommon.transactionEntity.setPayeeId(Constants.NOT_SET); } else { // if not, then IMPS transfer tp 3rd party transType = "Withdrawal"; mCommon.transactionEntity .setTransactionType(TransactionTypes.Withdrawal); mCommon.transactionEntity.setAccountToId(Constants.NOT_SET); mCommon.transactionEntity .setAmountTo(MoneyFactory.fromString(transAmount)); //if there is no to account found from mmex db, then check for payee //This will helps me to handle 3rd party transfer thru IMPS if (!toAccountDetails[6].isEmpty() && transPayee[0].isEmpty()) { transPayee = getPayeeDetails(toAccountDetails[6].trim()); } } } else { mCommon.transactionEntity.setAccountToId(Constants.NOT_SET); mCommon.transactionEntity.setAmountTo(MoneyFactory.fromString(transAmount)); } if (!transPayee[0].isEmpty()) { mCommon.transactionEntity.setPayeeId(parseInt(transPayee[0])); mCommon.payeeName = transPayee[1]; mCommon.transactionEntity.setCategoryId(parseInt(transPayee[2])); mCommon.transactionEntity.setSubcategoryId(parseInt(transPayee[3])); } t_intent.setAction(Intent.ACTION_INSERT); //Set the action break; default: //Update existing transaction transType = "Transfer"; AccountTransactionRepository repo = new AccountTransactionRepository(mContext); AccountTransaction txn = repo.load(txnId); if (txn != null) { if (txn.getTransactionType() != TransactionTypes.Transfer) { AccountRepository accountRepository = new AccountRepository(mContext); if (txn.getTransactionType() == TransactionTypes.Deposit) { toAccountID = txn.getAccountId(); toCurrencyID = accountRepository .loadCurrencyIdFor(txn.getAccountId()); } else { toAccountID = fromAccountID; toCurrencyID = fromCurrencyID; fromCurrencyID = accountRepository .loadCurrencyIdFor(txn.getAccountId()); } mCommon.transactionEntity = txn; mCommon.transactionEntity.setTransactionType(TransactionTypes.Transfer); mCommon.transactionEntity.setAccountId(fromAccountID); mCommon.transactionEntity.setAccountToId(toAccountID); //convert the to amount from the both currency details CurrencyService currencyService = new CurrencyService(mContext); mCommon.transactionEntity .setAmountTo(currencyService.doCurrencyExchange(fromCurrencyID, mCommon.transactionEntity.getAmount(), toCurrencyID)); mCommon.transactionEntity.setPayeeId(Constants.NOT_SET); String[] transCategory = getCategoryOrSubCategoryByName("Transfer"); if (!transCategory[0].isEmpty()) { mCommon.transactionEntity.setCategoryId(parseInt(transCategory[0])); mCommon.transactionEntity .setSubcategoryId(parseInt(transCategory[1])); } mCommon.transactionEntity.setNotes( mCommon.transactionEntity.getNotes() + "\n\n" + msgBody); t_intent.setAction(Intent.ACTION_EDIT); //Set the action } else //if transfer already exists, then do nothing { skipSaveTrans = true; } } } // Capture the details the for Toast String strExtracted = "Account = " + fromAccountName + "-" + fromAccountDetails[6] + "\n" + "Trans Amt = " + fromAccCurrencySymbl + " " + transAmount + ",\n" + "Payyee Name= " + transPayee[1] + "\n" + "Category ID = " + transPayee[2] + "\n" + "Sub Category ID = " + transPayee[3] + "\n" + "Trans Ref No. = " + transRefNo + "\n" + "Trans Type = " + transType + "\n"; //Must be commented for released version //mCommon.transactionEntity.setNotes(strExtracted); // Set the content for a transaction); t_intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_SOURCE, "SmsReceiverTransactions.java"); t_intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_ID, mCommon.transactionEntity.getId()); t_intent.putExtra(EditTransactionActivityConstants.KEY_ACCOUNT_ID, String.valueOf(mCommon.transactionEntity.getAccountId())); t_intent.putExtra(EditTransactionActivityConstants.KEY_TO_ACCOUNT_ID, String.valueOf(mCommon.transactionEntity.getAccountToId())); t_intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_CODE, mCommon.getTransactionType()); t_intent.putExtra(EditTransactionActivityConstants.KEY_PAYEE_ID, String.valueOf(mCommon.transactionEntity.getPayeeId())); t_intent.putExtra(EditTransactionActivityConstants.KEY_PAYEE_NAME, mCommon.payeeName); t_intent.putExtra(EditTransactionActivityConstants.KEY_CATEGORY_ID, String.valueOf(mCommon.transactionEntity.getCategoryId())); t_intent.putExtra(EditTransactionActivityConstants.KEY_SUBCATEGORY_ID, String.valueOf(mCommon.transactionEntity.getSubcategoryId())); t_intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_AMOUNT, String.valueOf(mCommon.transactionEntity.getAmount())); t_intent.putExtra(EditTransactionActivityConstants.KEY_NOTES, mCommon.transactionEntity.getNotes()); t_intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_DATE, new MmxDate().toDate()); t_intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_NUMBER, mCommon.transactionEntity.getTransactionNumber()); // validate and save the transaction if (skipSaveTrans == false) { if (validateData()) { if (saveTransaction()) { Toast.makeText(context, "MMEX: Bank Transaction Processed for: \n\n" + strExtracted, Toast.LENGTH_LONG).show(); autoTransactionStatus = true; } } //if transaction is not created automatically, then invoke notification or activity screen if (autoTransactionStatus == false) { startActivity(mContext, t_intent, null); //showNotification(t_intent, strExtracted); } } else { Toast.makeText(context, "MMEX: Skiping Bank Transaction updates SMS, because transaction exists with ref. no. " + transRefNo, Toast.LENGTH_LONG).show(); } //reset the value msgBody = ""; msgSender = ""; bundle = null; msgs = null; mCommon = null; skipSaveTrans = false; } } } } } } catch (Exception e) { Timber.e(e, "MMEX: Bank Transaction Process EXCEPTION"); } }
From source file:de.ub0r.android.smsdroid.SmsReceiver.java
static void handleOnReceive(final BroadcastReceiver receiver, final Context context, final Intent intent) { final String action = intent.getAction(); Log.d(TAG, "onReceive(context, ", action, ")"); final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakelock.acquire();/*from w ww . j a va 2 s . com*/ Log.i(TAG, "got wakelock"); Log.d(TAG, "got intent: ", action); try { Log.d(TAG, "sleep(", SLEEP, ")"); Thread.sleep(SLEEP); } catch (InterruptedException e) { Log.d(TAG, "interrupted in spinlock", e); e.printStackTrace(); } String text; if (SenderActivity.MESSAGE_SENT_ACTION.equals(action)) { handleSent(context, intent, receiver.getResultCode()); } else { boolean silent = false; if (shouldHandleSmsAction(context, action)) { Bundle b = intent.getExtras(); assert b != null; Object[] messages = (Object[]) b.get("pdus"); SmsMessage[] smsMessage = new SmsMessage[messages.length]; int l = messages.length; for (int i = 0; i < l; i++) { smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]); } text = null; if (l > 0) { // concatenate multipart SMS body StringBuilder sbt = new StringBuilder(); for (int i = 0; i < l; i++) { sbt.append(smsMessage[i].getMessageBody()); } text = sbt.toString(); // ! Check in blacklist db - filter spam String s = smsMessage[0].getDisplayOriginatingAddress(); // this code is used to strip a forwarding agent and display the orginated number as sender final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(PreferencesActivity.PREFS_FORWARD_SMS_CLEAN, false) && text.contains(":")) { Pattern smsPattern = Pattern.compile("([0-9a-zA-Z+]+):"); Matcher m = smsPattern.matcher(text); if (m.find()) { s = m.group(1); Log.d(TAG, "found forwarding sms number: (", s, ")"); // now strip the sender from the message Pattern textPattern = Pattern.compile("^[0-9a-zA-Z+]+: (.*)"); Matcher m2 = textPattern.matcher(text); if (text.contains(":") && m2.find()) { text = m2.group(1); Log.d(TAG, "stripped the message"); } } } final SpamDB db = new SpamDB(context); db.open(); if (db.isInDB(smsMessage[0].getOriginatingAddress())) { Log.d(TAG, "Message from ", s, " filtered."); silent = true; } else { Log.d(TAG, "Message from ", s, " NOT filtered."); } db.close(); if (action.equals(ACTION_SMS_NEW)) { // API19+: save message to the database ContentValues values = new ContentValues(); values.put("address", s); values.put("body", text); context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values); Log.d(TAG, "Insert SMS into database: ", s, ", ", text); } } updateNotificationsWithNewText(context, text, silent); } else if (ACTION_MMS_OLD.equals(action) || ACTION_MMS_MEW.equals(action)) { text = MMS_BODY; // TODO API19+ MMS code updateNotificationsWithNewText(context, text, silent); } } wakelock.release(); Log.i(TAG, "wakelock released"); }
From source file:org.xwalk.runtime.extension.api.messaging.MessagingSmsManager.java
public void registerIntentFilters() { mSmsReceiveReceiver = new MessagingReceiver(mMessagingHandler) { @Override/* ww w. j a v a 2 s . c o m*/ public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (null == bundle) { return; } Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; ++i) { try { JSONObject jsonMsg = new JSONObject(); jsonMsg.put("cmd", "received"); SmsMessage msgs = SmsMessage.createFromPdu((byte[]) pdus[i]); JSONObject jsData = new JSONObject(); jsonMsg.put("data", jsData); JSONObject jsMsg = new JSONObject(); jsData.put("message", jsMsg); jsMsg.put("messageID", ""); jsMsg.put("type", "sms"); jsMsg.put("serviceID", DEFAULT_SERVICE_ID); jsMsg.put("from", msgs.getOriginatingAddress()); SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); jsMsg.put("timestamp", sDateFormat.format(new java.util.Date())); jsMsg.put("body", msgs.getMessageBody().toString()); mMessaging.broadcastMessage(jsonMsg.toString()); } catch (JSONException e) { e.printStackTrace(); return; } } } }; mSmsSentReceiver = new MessagingReceiver(mMessagingHandler) { @Override public void onReceive(Context content, Intent intent) { boolean error = getResultCode() != Activity.RESULT_OK; String promise_id = intent.getStringExtra(EXTRA_MSGID); String smsMessage = intent.getStringExtra(EXTRA_MSGTEXT); String to = intent.getStringExtra(EXTRA_MSGTO); int instanceID = Integer.valueOf(intent.getStringExtra(EXTRA_MSGINSTANCEID)); try { JSONObject jsSentMsg = new JSONObject(); jsSentMsg.put("type", "sms"); jsSentMsg.put("from", ""); jsSentMsg.put("read", true); jsSentMsg.put("to", to); jsSentMsg.put("body", smsMessage); jsSentMsg.put("messageClass", "class1"); jsSentMsg.put("state", "sending"); jsSentMsg.put("deliveryStatus", error ? "error" : "pending"); JSONObject jsonMsgPromise = new JSONObject(); jsonMsgPromise.put("_promise_id", promise_id); jsonMsgPromise.put("cmd", "msg_smsSend_ret"); JSONObject jsData = new JSONObject(); jsonMsgPromise.put("data", jsData); jsData.put("error", error); jsData.put("body", jsSentMsg); mMessaging.postMessage(instanceID, jsonMsgPromise.toString()); JSONObject jsonMsgEvent = new JSONObject(); jsonMsgEvent.put("cmd", "sent"); jsonMsgEvent.put("data", jsSentMsg); mMessaging.broadcastMessage(jsonMsgEvent.toString()); } catch (JSONException e) { e.printStackTrace(); return; } ContentValues values = new ContentValues(); values.put("address", to); values.put("body", smsMessage); mMainActivity.getContentResolver().insert(Uri.parse("content://sms/sent"), values); } }; mSmsDeliveredReceiver = new MessagingReceiver(mMessagingHandler) { @Override public void onReceive(Context content, Intent intent) { boolean error = getResultCode() != Activity.RESULT_OK; String promise_id = intent.getStringExtra(EXTRA_MSGID); int instanceID = Integer.valueOf(intent.getStringExtra(EXTRA_MSGINSTANCEID)); try { JSONObject jsonMsg = new JSONObject(); jsonMsg.put("_promise_id", promise_id); jsonMsg.put("cmd", error ? "deliveryerror" : "deliverysuccess"); JSONObject jsData = new JSONObject(); jsonMsg.put("data", jsData); JSONObject jsEvent = new JSONObject(); jsData.put("event", jsEvent); jsEvent.put("serviceID", DEFAULT_SERVICE_ID); jsEvent.put("messageID", ""); jsEvent.put("recipients", ""); SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); jsEvent.put("deliveryTimestamps", sDateFormat.format(new java.util.Date())); jsData.put("error", error); mMessaging.postMessage(instanceID, jsonMsg.toString()); } catch (JSONException e) { e.printStackTrace(); return; } } }; mSmsServiceReceiver = new MessagingReceiver(mMessagingHandler) { @Override public void onReceive(Context content, Intent intent) { try { JSONObject jsonMsg = new JSONObject(); jsonMsg.put("cmd", checkService(DEFAULT_SERVICE_ID) ? "serviceadded" : "serviceremoved"); JSONObject jsData = new JSONObject(); jsonMsg.put("data", jsData); JSONObject jsEvent = new JSONObject(); jsData.put("event", jsEvent); jsEvent.put("serviceID", DEFAULT_SERVICE_ID); mMessaging.broadcastMessage(jsonMsg.toString()); } catch (JSONException e) { e.printStackTrace(); return; } } }; mMainActivity.registerReceiver(mSmsReceiveReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED")); mMainActivity.registerReceiver(mSmsSentReceiver, new IntentFilter("SMS_SENT")); mMainActivity.registerReceiver(mSmsDeliveredReceiver, new IntentFilter("SMS_DELIVERED")); mMainActivity.registerReceiver(mSmsServiceReceiver, new IntentFilter("android.intent.action.SIM_STATE_CHANGED")); }
From source file:uk.ac.ucl.excites.sapelli.relay.BackgroundService.java
/** * Register an SMS Data (Binary) Receiver *///from w w w .j ava2s . c o m private void registerSmsReceiver() { smsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Debug.i("Received Binary SMS"); Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; if (null != bundle) { // In telecommunications the term (PDU) means protocol data // unit. // There are two ways of sending and receiving SMS messages: // by text mode and by PDU (protocol description unit) mode. // The PDU string contains not only the message, but also a // lot of meta-information about the sender, his SMS service // center, the time stamp etc // It is all in the form of hexa-decimal octets or decimal // semi-octets. Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { // Create the Message msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); // Get Message Parameters SmsObject receivedSms = new SmsObject(); receivedSms.setTelephoneNumber(msgs[i].getOriginatingAddress()); receivedSms.setMessageTimestamp(msgs[i].getTimestampMillis()); receivedSms.setMessageData(Base64.encodeToString(msgs[i].getUserData(), Base64.CRLF)); Debug.d("Received SMS and it's content hash is: " + BinaryHelpers .toHexadecimealString(Hashing.getMD5Hash(msgs[i].getUserData()).toByteArray())); // Store the SmsObject to the db dao.storeSms(receivedSms); } } // This will stop the Broadcast and not allow the message to // be interpreted by the default Android app or other apps abortBroadcast(); } }; // Set up the Receiver Parameters IntentFilter mIntentFilter = new IntentFilter(); mIntentFilter.setPriority(999); mIntentFilter.addAction("android.intent.action.DATA_SMS_RECEIVED"); mIntentFilter.addDataScheme("sms"); // Set the Port that is listening to mIntentFilter.addDataAuthority("*", "2013"); // mIntentFilter.addDataType(type) registerReceiver(smsReceiver, mIntentFilter); Debug.d("Set up BinarySMS receiver."); }
From source file:com.piusvelte.sonet.core.SonetService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else/*from ww w . ja v a 2 s . c om*/ putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(SonetService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(SonetService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(SonetService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(SonetService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Sonet.default_message_bg_color; int profile_bg_color = Sonet.default_message_bg_color; int friend_bg_color = Sonet.default_friend_bg_color; boolean icon = true; int status_count = Sonet.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(SonetService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Sonet.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(SonetService.this, widget, Sonet.INVALID_ACCOUNT_ID); } initAccountSettings(SonetService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(SonetService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(SonetService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(SonetService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(SonetService.this, 0, (Sonet .getPackageIntent(SonetService.this, SonetNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }