SmsReceiver.java 2.36 KB
package com.example.talktalkspeak;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsMessage;
import android.util.Log;
import java.util.Date;

public class SmsReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {

            SmsMessage[] messages = parseSmsMessage(intent.getExtras());
            if (messages.length > 0) {
                sendToActivity(context, messages[0].getOriginatingAddress(), messages[0].getMessageBody().toString(), new Date(messages[0].getTimestampMillis()));
            }
        }
    }

    private String GetName(Context context, String str) {
        String name = "str";
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(str));
        Cursor cursor = context.getContentResolver().query(uri, new String[]{"display_name"}, (String) null, (String[]) null, (String) null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                name = cursor.getString(0);
            }
            cursor.close();
        }
        return name;
    }

    private void sendToActivity(Context context, String sender, String contents, Date receivedDate) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(872415232);
        intent.putExtra("sender", sender);
        intent.putExtra("contents", contents);
        intent.putExtra("class", "SMS");
        Log.d("SMSToSpeech", "Sender :" + sender);
        Log.d("SMSToSpeech", "contents : " + contents);
        context.startActivity(intent);
    }

    private SmsMessage[] parseSmsMessage(Bundle bundle) {
        Object[] objs = (Object[]) bundle.get("pdus");
        SmsMessage[] messages = new SmsMessage[objs.length];
        for (int i = 0; i < objs.length; i++) {
            if (Build.VERSION.SDK_INT >= 23) {
                messages[i] = SmsMessage.createFromPdu((byte[]) objs[i], bundle.getString("format"));
            } else {
                messages[i] = SmsMessage.createFromPdu((byte[]) objs[i]);
            }
        }
        return messages;
    }
}