我正在制作一个应用程序,我会收听所有收到的短信,并将它们安全地发送到我服务器上的数据库。我还要发送所有收到的短信的显示名称,实现这一目的的最佳方法是什么?有没有办法可以使用传入的消息来完成它,或者唯一的方法是创建一个函数来搜索我的联系人与smsMessage [0]相同的数字。我从传入的SMS消息中得到.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
可能是什么问题?任何帮助都非常感谢。
答案 0 :(得分:0)
我认为问题可能是BroadcastReceiver没有从Context继承。在获取内容解析器时,需要使用传递给onReceive()的Context。因此,在getContactName()方法中,而不是:
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
你应该使用它:
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);