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
可能是什麼問題呢?任何幫助真的很感激。