2
我正在制作一个应用程序,用于监听所有传入的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
可能是什么问题呢?任何帮助真的很感激。