2013-03-12 27 views
0

我想创建一个应用程序,我只想得到最近收到的短信的发件人信息(电话号码,日期),我想发送回复消息那个特定的数字。我怎样才能访问最近收到的短信的编号在android

我试过这段代码,怎样才能得到最近收到的短信的发件人信息?

Bundle bundle = intent.getExtras(); 
SmsMessage[] msgs = null; 
String string = ""; 
String phone = ""; 

if (bundle != null) 
{ 
    //---receive the SMS message-- 
    Object[] pdus = (Object[]) bundle.get("pdus"); 
    msgs = new SmsMessage[pdus.length];    
    for (int i=0; i<msgs.length; i++){ 
     msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
     phone = msgs[i].getOriginatingAddress(); // Here you can get the phone number of SMS sender. 
     string += msgs[i].getMessageBody().toString(); // Here you can get the message body. 
     } 
} 

反正是有得到的消息发送号码不延长广播接收器?反正从消息日志存取权限?

+0

@Hardik中,我应该延长广播reciever? – 2013-03-12 06:42:23

+0

为什么你不想扩展'BroadcastReceiver'?可以从收件箱读取消息(通过“ContentProvider”)[但不是每个设备](http://android-developers.blogspot.ch/2010/05/be-careful-with-content-providers.html) ! – faceman 2013-03-12 07:32:45

回答

1

一步按照这个例子步:

SMS Messaging in Android

包含接收和回复短信,还包括完整的代码!接收短信是通过Broadcast Receiver


反正是有得到的消息发送号码不延长 广播接收器?反正从消息日志访问?

您可以通过访问Content Providers现有的SMS数据库,但广播接收器和更进步后的消息到达那里“看”的时候是写在Android的数据库中的新信息。


我怎样才能得到最近收到的短信的发送者的信息?

答案这条线:

phone = msgs[i].getOriginatingAddress(); // Here you can get the phone number of SMS sender. 

数量在模拟器中的规定数量由网络提供商提供的发送者“号”,它也可以是文字。

1

下面的代码会给你接收的文本消息的编号。

Uri uri = Uri.parse("content://sms/inbox"); 
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    int i =0; 
    String[] number = new String[cursor.getCount()]; 
    while (cursor.moveToNext()) { 
     number[i] = (String) cursor.getString(cursor.getColumnIndex("address")); 
     i++;       
     } 
    } 

为了得到最近收到的短信数量,你可以访问

String mostRecentNumber = number[0];