2011-07-24 3 views
2

私はすべての着信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 

問題がある可能性がありますか?どんな助けでも本当に感謝しています。

答えて

0

私は、BroadcastReceiverがContextを継承しないことが問題だと思います。 contentresolverを取得するときに、onReceive()に渡されるコンテキストを使用する必要があります。だから、これに代えてgetContactName()メソッドで:

Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); 

Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); 

あなたはこれを使用する必要があります

関連する問題