SmsReceiver.java 2.61 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.text.SimpleDateFormat;
import java.util.Date;

public class SmsReceiver extends BroadcastReceiver {
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    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("receivedDate", format.format(receivedDate));
        intent.putExtra("class", "SMS");
        Log.d("SMSToSpeech", "Sender :" + sender);
        Log.d("SMSToSpeech", "contents : " + contents);
        Log.d("SMSToSpeech", "receivedDate : " + receivedDate);
        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;
    }
}