【发布时间】:2011-10-12 02:55:35
【问题描述】:
我正在制作一个应用程序,我可以在其中收听所有传入的 SMS 消息并将它们安全地发送到我服务器上的数据库。我还想发送所有收到的 SMS 消息的显示名称,最好的方法是什么?有没有一种方法可以处理传入的消息,或者实现此目的的唯一方法是创建一个函数,该函数将在我的联系人中搜索与我从传入的 SMS 消息中获得的 smsMessage[0].getOriginatingAddress() 相同的号码.这是我找到的函数和传入消息的代码:
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
// show first message
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.qas.im/web/add_sms.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("from", smsMessage[0].getOriginatingAddress()));
nameValuePairs.add(new BasicNameValuePair("msg", smsMessage[0].getMessageBody()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
httpclient.execute(httppost);
} catch (ClientProtocolException e) {} catch (IOException e) {}
Toast toast = Toast.makeText(context, "Sent to Server \n\n" + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
public String getContactName(final String phoneNumber)
{
Uri uri;
String[] projection;
if (Build.VERSION.SDK_INT >= 5)
{
uri = Uri.parse("content://com.android.contacts/phone_lookup");
projection = new String[] { "display_name" };
}
else
{
uri = Uri.parse("content://contacts/phones/filter");
projection = new String[] { "name" };
}
uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
它工作得很好,但是 getContactName() 有一个错误:
The method getContentResolver() is undefined for the type SMSReceiver
可能是什么问题?非常感谢任何帮助。
【问题讨论】:
标签: android android-contacts phone-number