SmsReceiver.java
2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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;
}
}