Search in sources :

Example 21 with SMS

use of dev.sagar.smsblocker.tech.beans.SMS in project SMSBlocker by sagarpawardev.

the class InboxUtil method getLatestMsgs.

/**
 * Helps in getting most recent SMSes from all contacts
 * @return key-value pair of contact_number and most_recent_message <Contact Number, Most Recent Message>
 */
public IndexedHashMap<String, SMS> getLatestMsgs() {
    final String methodName = "getLatestMsgs()";
    log.justEntered(methodName);
    final String m_threadid = Telephony.Sms.Conversations.THREAD_ID;
    final String mSnippet = Telephony.Sms.Conversations.SNIPPET;
    final String mMessageCount = Telephony.Sms.Conversations.MESSAGE_COUNT;
    final String mDate = Telephony.Sms.Conversations.DATE;
    ContentResolver mContentResolver = context.getContentResolver();
    Uri mConversationUri = Telephony.Sms.Conversations.CONTENT_URI;
    IndexedHashMap<String, SMS> smsMap = new IndexedHashMap<>();
    String[] mProjection = { m_threadid, mSnippet, mMessageCount };
    String mSelection = "";
    String[] mSelectionArgs = {};
    String mSortOrder = mDate + " DESC";
    Cursor mConversation = dbService.query(mContentResolver, mConversationUri, mProjection, mSelection, mSelectionArgs, mSortOrder);
    log.info(methodName, "Reading Messages..");
    if (mConversation == null) {
        log.info(methodName, "Conversation Query returned null cursor");
        return smsMap;
    }
    log.info(methodName, "Conversation Count: " + mConversation.getCount());
    // Collecting ThreadId from Conversation Starts
    String[] conversations = new String[mConversation.getCount()];
    int count = 0;
    while (mConversation.moveToNext()) {
        conversations[count++] = mConversation.getString(mConversation.getColumnIndexOrThrow(m_threadid));
    }
    Uri mLatestSmsUri = Telephony.Sms.CONTENT_URI;
    String[] mLatestSmsProjection = { _id, address, body, read, date, subscriptionId, type };
    StringBuilder sb = new StringBuilder(threadId + " IN (");
    for (int i = 0; i < conversations.length; i++) {
        sb.append("?");
        if (i != conversations.length - 1) {
            // If not last index
            sb.append(",");
        }
    }
    sb.append(")");
    String mLatestSmsSelection = sb.toString();
    String[] mLatestSmsSelectionArgs = conversations;
    String mLatestSmsSortOrder = this.date + " desc";
    // -- Collecting ThreadId from Conversation Ends
    Cursor mLatestSmsCursor = mContentResolver.query(mLatestSmsUri, mLatestSmsProjection, mLatestSmsSelection, mLatestSmsSelectionArgs, mLatestSmsSortOrder);
    if (mLatestSmsCursor == null) {
        log.info(methodName, "Latest SMS Query returned null cursor");
        return smsMap;
    }
    while (mLatestSmsCursor.moveToNext()) {
        String id = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this._id));
        String from = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.address));
        String body = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.body));
        int serviceCenter = mLatestSmsCursor.getInt(mLatestSmsCursor.getColumnIndexOrThrow(this.subscriptionId));
        boolean readState = mLatestSmsCursor.getInt(mLatestSmsCursor.getColumnIndex(this.read)) == 1;
        long time = mLatestSmsCursor.getLong(mLatestSmsCursor.getColumnIndexOrThrow(this.date));
        long type = mLatestSmsCursor.getLong(mLatestSmsCursor.getColumnIndexOrThrow(this.type));
        if (smsMap.containsKey(from)) {
            continue;
        }
        SMS sms = new SMS();
        sms.setId(id);
        sms.setAddress(from);
        sms.setBody(body);
        sms.setRead(readState);
        sms.setDateTime(time);
        sms.setType(type);
        sms.setSubscription(serviceCenter);
        log.debug(methodName, from + "\t" + body + "\t" + id);
        smsMap.put(from, sms);
    }
    mLatestSmsCursor.close();
    mConversation.close();
    log.returning(methodName);
    return smsMap;
}
Also used : IndexedHashMap(dev.sagar.smsblocker.tech.datastructures.IndexedHashMap) SMS(dev.sagar.smsblocker.tech.beans.SMS) Cursor(android.database.Cursor) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver)

Example 22 with SMS

use of dev.sagar.smsblocker.tech.beans.SMS in project SMSBlocker by sagarpawardev.

the class SMSUtil method sendSMS.

/**
 * This method sends sms to specified contact number
 * @param phoneNo
 * @param msg
 */
public SMS sendSMS(String phoneNo, String msg) {
    String methodName = "sendSMS()";
    log.justEntered(methodName);
    SMS sms = null;
    try {
        SmsManager smsManager = SmsManager.getDefault();
        int subsId = smsManager.getSubscriptionId();
        boolean isAppDefault = PermissionUtilSingleton.getInstance().isAppDefault(context);
        sms = new SMS();
        sms.setRead(true);
        sms.setType(SMS.TYPE_QUEUED);
        sms.setDateTime(System.currentTimeMillis());
        sms.setBody(msg);
        sms.setAddress(phoneNo);
        sms.setSubscription(subsId);
        ArrayList<String> parts = smsManager.divideMessage(msg);
        ArrayList<PendingIntent> sentPIntents = null;
        ArrayList<PendingIntent> deliverPIntents = null;
        if (isAppDefault) {
            log.info(methodName, "Saving SMS in DB");
            // Save in DataProvider
            InboxUtil inboxUtil = new InboxUtil(context);
            String id = inboxUtil.insertSMS(sms);
            sms.setId(id);
            log.info(methodName, "SMS Saved with id: " + id);
            log.info(methodName, "Creating Delivery and Sent Receivers");
            int numParts = parts.size();
            sentPIntents = new ArrayList<>();
            deliverPIntents = new ArrayList<>();
            for (int i = 0; i < numParts; i++) {
                Intent sentIntent = new Intent(context, SMSSentReceiver.class);
                Bundle sendBasket = new Bundle();
                Intent deliverIntent = new Intent(context, SMSDeliveredReceiver.class);
                Bundle deliverBasket = new Bundle();
                sendBasket.putInt(SMSSentReceiver.KEY_PART_INDEX, i);
                deliverBasket.putSerializable(SMSDeliveredReceiver.KEY_PART_INDEX, i);
                String strSms = gson.toJson(sms);
                sendBasket.putString(SMSSentReceiver.KEY_SMS, strSms);
                deliverBasket.putSerializable(SMSDeliveredReceiver.KEY_SMS, sms);
                sentIntent.putExtras(sendBasket);
                deliverIntent.putExtras(deliverBasket);
                sendBasket.putInt(SMSSentReceiver.KEY_TOTAL_PARTS, numParts);
                deliverBasket.putSerializable(SMSDeliveredReceiver.KEY_TOTAL_PARTS, numParts);
                log.info(methodName, "putting sent action in pendingIntent: " + ActionCode.SMS_SENT);
                sentIntent.setAction(ActionCode.SMS_SENT);
                deliverIntent.setAction(ActionCode.SMS_DELIVERED);
                PendingIntent sentPIntent = PendingIntent.getBroadcast(context, RequestCode.SMS_SENT, sentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                PendingIntent deliverPIntent = PendingIntent.getBroadcast(context, RequestCode.SMS_DELIVERED, deliverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                sentPIntents.add(sentPIntent);
                deliverPIntents.add(deliverPIntent);
            }
            log.info(methodName, "Delivery and Sent Receivers Created");
        }
        // Send SMS
        log.info(methodName, "Trying to Send SMS");
        smsManager.sendMultipartTextMessage(phoneNo, null, parts, sentPIntents, deliverPIntents);
        // smsManager.sendTextMessage(phoneNo, null, msg, null, null);
        log.info(methodName, "SMS Queued");
    } catch (Exception e) {
        log.error(methodName, "Sending Failed");
        Toast.makeText(context, "Give File permissions manually. (Debug)", Toast.LENGTH_LONG).show();
        log.error(methodName, e);
        e.printStackTrace();
    }
    log.returning(methodName);
    return sms;
}
Also used : Bundle(android.os.Bundle) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) SmsManager(android.telephony.SmsManager) SMS(dev.sagar.smsblocker.tech.beans.SMS) PendingIntent(android.app.PendingIntent)

Example 23 with SMS

use of dev.sagar.smsblocker.tech.beans.SMS in project SMSBlocker by sagarpawardev.

the class DBServiceSingleton method refreshConversations.

/**
 * Refreshes Conversation Shadow Database
 * @param context Context
 * @return Returns number of rows present in ShadowConversation
 */
public int refreshConversations(Context context) {
    String methodName = "refreshConversation()";
    log.justEntered(methodName);
    int result = 0;
    DBHelper mDBHelper = new DBHelper(context);
    // Content MAP
    ContentResolver contentResolver = context.getContentResolver();
    Uri mUriSMS = Telephony.Sms.CONTENT_URI;
    // Read Old Conversation DB Rows Starts
    log.info(methodName, "Reading old Address and Date rows");
    String[] mOldProjection = { "*" };
    SQLiteDatabase readDB = mDBHelper.getReadableDatabase();
    Cursor mOldCursor = readDB.query(Converesation.TABLE_NAME, mOldProjection, null, null, null, null, null);
    HashMap<String, SMS> oldMap = new HashMap<>();
    if (mOldCursor != null) {
        log.info(methodName, "Reading Address and Date Count:" + mOldCursor.getCount());
        while (mOldCursor.moveToNext()) {
            String address = mOldCursor.getString(mOldCursor.getColumnIndexOrThrow(this.address_local));
            /*String normalizeAddress = PhoneNumberUtils.normalizeNumber(originalAddress);
                String address = normalizeAddress;
                if(address.length() < 9){ //If Number is like VK-Voda its normalized code is 3856778
                    address = originalAddress;
                }*/
            log.info(methodName, "Reading contact details: " + address);
            long date = mOldCursor.getLong(mOldCursor.getColumnIndexOrThrow(this.date_local));
            String id = mOldCursor.getString(mOldCursor.getColumnIndexOrThrow(this._id_local));
            String body = mOldCursor.getString(mOldCursor.getColumnIndexOrThrow(this.body_local));
            int subscriptionId = mOldCursor.getInt(mOldCursor.getColumnIndexOrThrow(this.subscriptionId_local));
            String read = mOldCursor.getString(mOldCursor.getColumnIndex(this.read_local));
            boolean bRead = (read.equals("0") || read.equalsIgnoreCase("false"));
            long type = mOldCursor.getLong(mOldCursor.getColumnIndexOrThrow(this.type_local));
            SMS sms = new SMS();
            sms.setId(id);
            sms.setAddress(address);
            sms.setDateTime(date);
            sms.setId(id);
            sms.setBody(body);
            sms.setSubscription(subscriptionId);
            sms.setRead(bRead);
            sms.setType(type);
            oldMap.put(address, sms);
        }
        mOldCursor.close();
    } else {
        log.error(methodName, "OLD Conversation Query returned null cursor");
    }
    // -- Read Old Conversation DB Rows Ends
    // Reading Latest SMS DB Rows from ContentProvider Starts
    log.info(methodName, "Reading Latest SMS from Contact");
    String[] mProjection = new String[] { "*" };
    String mSelection = "";
    String[] mSelectionArgs = {};
    String mSortOrder = this.date + " DESC";
    HashSet<String> doneSet = new HashSet<>();
    HashMap<String, Integer> unreadCountMap = new HashMap<>();
    SQLiteDatabase writableDB = mDBHelper.getWritableDatabase();
    Cursor mLatestSmsCursor = contentResolver.query(mUriSMS, mProjection, mSelection, mSelectionArgs, mSortOrder);
    int tempCount = 0;
    if (mLatestSmsCursor != null) {
        log.info(methodName, "Reading latest sms from contact count:" + mLatestSmsCursor.getCount());
        while (mLatestSmsCursor.moveToNext()) {
            String id = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this._id));
            String address = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.address));
            String body = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.body));
            String subscriptionId = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.subscriptionId));
            String read = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.read));
            long date = mLatestSmsCursor.getLong(mLatestSmsCursor.getColumnIndexOrThrow(this.date));
            long type = mLatestSmsCursor.getLong(mLatestSmsCursor.getColumnIndexOrThrow(this.type));
            String threadId = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.threadId));
            String person = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.person));
            String protocol = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.protocol));
            String status = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.status));
            String reply_path_present = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.reply_path_present));
            String subject = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.subject));
            String locked = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.locked));
            String errorCode = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.errorCode));
            /*String normalizedAddress = PhoneNumberUtils.normalizeNumber(address);
                String address = normalizedAddress;
                if(address.length() < 8){ //If Number is like VK-Voda its normalized code is 3856778
                    address = originalAddress;
                }*/
            log.info(methodName, "Reading SMS from contactNumber: " + address + " ");
            ContentValues values = new ContentValues();
            values.put(this._id_local, id);
            values.put(this.address_local, address);
            values.put(this.body_local, body);
            values.put(this.subscriptionId_local, subscriptionId);
            values.put(this.read_local, read);
            values.put(this.date_local, date);
            values.put(this.type_local, type);
            values.put(this.threadId_local, threadId);
            values.put(this.person_local, person);
            values.put(this.protocol_local, protocol);
            values.put(this.status_local, status);
            values.put(this.reply_path_present_local, reply_path_present);
            values.put(this.subject_local, subject);
            values.put(this.locked_local, locked);
            values.put(this.errorCode_local, errorCode);
            // If unread increment count
            log.info(methodName, "Raw Unread value: " + read + " for address: " + address);
            // If object is saved as integer or boolean
            boolean bUnread = (read.equals("0") || read.equalsIgnoreCase("false"));
            if (bUnread) {
                Integer unreadCount = unreadCountMap.get(address);
                int count = unreadCount == null ? 0 : unreadCount;
                count++;
                // Increment count here
                unreadCountMap.put(address, count);
                values.put(this.unreadCount_local, count);
                log.info(methodName, "Adding unread count: " + count + " for address: " + address);
            }
            // If value is already in Map then go to next value
            if (doneSet.contains(address))
                continue;
            SMS oldSMS = oldMap.get(address);
            // if(oldSMS == null) continue; //Just in case if nothing found
            long oldDate = oldMap.get(address) == null ? 0 : oldMap.get(address).getDateTime();
            // if(oldDate >= date) continue; //If oldDate is greater than or equals current date ignore message
            log.error(methodName, "Olddate: " + oldDate + " newdate:" + date + " address:" + address + " type:" + type);
            if (oldSMS != null && id.equals(oldSMS.getId()) && address.equals(oldSMS.getAddress())) {
                doneSet.add(address);
                // If SMS is same as older ones
                continue;
            }
            if (oldMap.containsKey(address)) {
                String whereClause = this.address_local + " = ?";
                String[] whereArgs = { address };
                writableDB.update(Converesation.TABLE_NAME, values, whereClause, whereArgs);
            } else {
                writableDB.insert(Converesation.TABLE_NAME, null, values);
            }
            doneSet.add(address);
            result++;
        }
        mLatestSmsCursor.close();
    } else {
        log.error(methodName, "SMS Query returned null cursor");
    }
    // -- Reading Latest SMS DB Rows from ContentProvider Ends
    // Create a map of all contacts Starts
    Uri mContactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] mContactProjection = { this.photoUri, this.photoUriThumbnail, ContactsContract.CommonDataKinds.Phone.NUMBER, this.contactName };
    Map<String, ContactDetails> mContactMap = new HashMap<>();
    if (permUtil.hasPermission(context, Permission.READ_CONTACTS)) {
        Cursor mContactCursor = contentResolver.query(mContactUri, mContactProjection, null, null, null);
        if (mContactCursor != null) {
            while (mContactCursor.moveToNext()) {
                String contactName = mContactCursor.getString(mContactCursor.getColumnIndex(this.contactName));
                String photoThumb = mContactCursor.getString(mContactCursor.getColumnIndex(this.photoUriThumbnail));
                String photoUri = mContactCursor.getString(mContactCursor.getColumnIndex(this.photoUri));
                String address = mContactCursor.getString(mContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                /*String normalizedAddress = PhoneNumberUtils.normalizeNumber(address);*/
                ContactDetails contact = new ContactDetails();
                contact.name = contactName;
                contact.photoThumbUri = photoThumb;
                contact.photoUri = photoUri;
                contact.address = address;
                String formattedAddress = phoneUtils.formatNumber(context, contact.address);
                mContactMap.put(formattedAddress, contact);
                // TODO Default country to format number
                log.info(methodName, "Found contactName: " + contactName + " for address: " + address + " In new map: " + doneSet.contains(address));
            }
            mContactCursor.close();
        } else {
            log.error(methodName, "Nothing in Contacts Cursor for " + address);
        }
    } else {
        log.error(methodName, "No contact read permissions");
    }
    // Update Photo in Database Starts
    for (String key : doneSet) {
        String formattedKey = phoneUtils.formatNumber(context, key);
        ContactDetails contact = mContactMap.get(formattedKey);
        if (contact == null) {
            // In case address does not exists in Contacts
            continue;
        }
        ContentValues values = new ContentValues();
        values.put(this.contactName_local, contact.name);
        values.put(this.photoUri_local, contact.photoUri);
        values.put(this.photoUriThumbnail_local, contact.photoThumbUri);
        String whereClause = this.address_local + " LIKE ?";
        String encodedAddress = phoneUtils.encode(contact.address);
        String[] whereArgs = { encodedAddress };
        writableDB.update(Converesation.TABLE_NAME, values, whereClause, whereArgs);
    }
    // -- Update Photo in Database Ends
    // Update unread_count in Conversation Starts
    StringBuilder sbRawQuery = new StringBuilder();
    sbRawQuery.append(" UPDATE ");
    sbRawQuery.append(Converesation.TABLE_NAME);
    sbRawQuery.append(" SET " + Converesation.COLUMN_NAME_UNREAD_COUNT + "= CASE " + Converesation.COLUMN_NAME_ADDRESS);
    ArrayList<Integer> alValues = new ArrayList<>();
    Set<String> addresses = unreadCountMap.keySet();
    for (String mAddress : addresses) {
        Integer iUnreadCount = unreadCountMap.get(mAddress);
        int unreadCount = iUnreadCount == null ? 0 : iUnreadCount;
        sbRawQuery.append(" WHEN '" + mAddress + "' THEN " + unreadCount);
        alValues.add(unreadCount);
    }
    sbRawQuery.append(" END WHERE ");
    sbRawQuery.append(Converesation.COLUMN_NAME_ADDRESS);
    sbRawQuery.append(" IN (");
    for (String mAddress : addresses) {
        sbRawQuery.append("'" + mAddress + "',");
    }
    // Deleting , at end
    sbRawQuery.deleteCharAt(sbRawQuery.length() - 1);
    sbRawQuery.append(")");
    if (addresses.size() > 0) {
        // Updating empty database does not make sense and App crashes as well
        String[] strArgs = null;
        String rawQuery = sbRawQuery.toString();
        log.debug(methodName, "Formed Query: " + rawQuery);
        Cursor c = writableDB.rawQuery(rawQuery, strArgs);
        log.info(methodName, "Updated rows: " + c.getCount());
        // Query won't update unless moveToFirst() or close() is called
        c.close();
    }
    // -- Update unread_count in Conversation Starts
    // TODO: Delete Condition when conversation is removed from main database but exists in Local Database
    writableDB.close();
    mDBHelper.close();
    log.returning(methodName);
    return result;
}
Also used : ContentValues(android.content.ContentValues) HashMap(java.util.HashMap) DBHelper(dev.sagar.smsblocker.tech.service.helper.DBHelper) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) SMS(dev.sagar.smsblocker.tech.beans.SMS) HashSet(java.util.HashSet)

Example 24 with SMS

use of dev.sagar.smsblocker.tech.beans.SMS in project SMSBlocker by sagarpawardev.

the class NotificationBroadcastReceiver method onReceive.

@Override
public void onReceive(Context context, Intent intent) {
    if (REPLY_ACTION.equals(intent.getAction())) {
        // do whatever you want with the message. Send to the server or add to the db.
        // for this tutorial, we'll just show it in a toast;
        CharSequence message = getReplyMessage(intent);
        Bundle bundle = intent.getExtras();
        String lAddress = bundle.getString(KEY_ADDRESS);
        int notifId = bundle.getInt(KEY_NOTIF_ID);
        SMSUtil smsUtil = new SMSUtil(context);
        SMS sms = smsUtil.sendSMS(lAddress, message.toString());
        if (sms != null) {
            NotificationUtilSingleton.getInstance().notifySMSSent(context, notifId);
        } else {
            NotificationUtilSingleton.getInstance().notifySendingFailed(context, notifId);
        }
    }
}
Also used : Bundle(android.os.Bundle) SMS(dev.sagar.smsblocker.tech.beans.SMS) SMSUtil(dev.sagar.smsblocker.tech.utils.SMSUtil)

Example 25 with SMS

use of dev.sagar.smsblocker.tech.beans.SMS in project SMSBlocker by sagarpawardev.

the class SMSDeliveredReceiver method resultCanceled.

private void resultCanceled(Context context, Intent intent) {
    final String methodName = "resultCanceled(Context, Intent)";
    log.justEntered(methodName);
    Bundle basket = intent.getExtras();
    SMS sms = (SMS) basket.getSerializable(KEY_SMS);
    broadcastLocalSMS(context, sms, KEY_DELIVERY_CANCELLED);
    log.returning(methodName);
}
Also used : Bundle(android.os.Bundle) SMS(dev.sagar.smsblocker.tech.beans.SMS)

Aggregations

SMS (dev.sagar.smsblocker.tech.beans.SMS)27 Bundle (android.os.Bundle)11 ContentResolver (android.content.ContentResolver)5 Uri (android.net.Uri)5 ArrayList (java.util.ArrayList)5 Cursor (android.database.Cursor)4 ContentValues (android.content.ContentValues)3 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)3 DBHelper (dev.sagar.smsblocker.tech.service.helper.DBHelper)3 HashSet (java.util.HashSet)2 Animator (android.animation.Animator)1 ArgbEvaluator (android.animation.ArgbEvaluator)1 ValueAnimator (android.animation.ValueAnimator)1 PendingIntent (android.app.PendingIntent)1 Intent (android.content.Intent)1 SQLiteOpenHelper (android.database.sqlite.SQLiteOpenHelper)1 Typeface (android.graphics.Typeface)1 Handler (android.os.Handler)1 SmsManager (android.telephony.SmsManager)1 SmsMessage (android.telephony.SmsMessage)1