【问题标题】:Read inbox messages of a particular number and display them in an activity阅读特定号码的收件箱消息并在活动中显示它们
【发布时间】:2011-08-22 05:19:04
【问题描述】:

我正在尝试从收件箱中读取消息并将其显示在活动中。我的活动包含一个按钮和列表视图。当我单击该按钮时,将显示收件箱中的所有消息。但我的要求是我需要查看来自特定号码的消息。当我单击单击按钮时从该号码收到消息时,我的应用程序未运行,只有特定消息(与特定号码相关联)必须更新。 这是相关的代码。

myActivity.java:

public class SecureMessagesActivity extends Activity implements OnClickListener, OnItemClickListener {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme( android.R.style.Theme_Light );
        setContentView(R.layout.main);
        this.findViewById( R.id.UpdateList ).setOnClickListener( this );
    }

    ArrayList<String> smsList = new ArrayList<String>();

    public void onItemClick( AdapterView<?> parent, View view, int pos, long id ) {
        try {
            String[] splitted = smsList.get( pos ).split("\n"); 
            String sender = splitted[0];
            String encryptedData = "";

            for ( int i = 1; i < splitted.length; ++i ) {
                encryptedData += splitted[i];
            }
            String data = sender + "\n" + StringCryptor.decrypt( new String(SmsReceiver.PASSWORD), encryptedData );
            Toast.makeText( this, data, Toast.LENGTH_SHORT ).show();
        } 
        catch (Exception e) {
                e.printStackTrace();
        }
    }

    public void onClick( View v ) {
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query( Uri.parse( "content://sms/inbox" ), null, null, null, null);

        int indexBody = cursor.getColumnIndex( SmsReceiver.BODY );
        int indexAddr = cursor.getColumnIndex( SmsReceiver.ADDRESS );

        if ( indexBody < 0 || !cursor.moveToFirst() ) return;

        smsList.clear();

        do {
            String str = "Sender: " + cursor.getString( indexAddr ) + "\n" + cursor.getString( indexBody );
            smsList.add( str );
        }
        while( cursor.moveToNext() );

        ListView smsListView = (ListView) findViewById( R.id.SMSList );
        smsListView.setAdapter( new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, smsList) );
        smsListView.setOnItemClickListener( this );
    }
} 

SmsReceiver.java:

public class SmsReceiver extends BroadcastReceiver {
    public static final String SMS_EXTRA_NAME = "pdus";
    public static final String SMS_URI = "content://sms";

    public static final String ADDRESS = "address";
    public static final String PERSON = "person";
    public static final String DATE = "date";
    public static final String READ = "read";
    public static final String STATUS = "status";
    public static final String TYPE = "type";
    public static final String BODY = "body";
    public static final String SEEN = "seen";

    public static final int MESSAGE_TYPE_INBOX = 1;
    public static final int MESSAGE_TYPE_SENT = 2;

    public static final int MESSAGE_IS_NOT_READ = 0;
    public static final int MESSAGE_IS_READ = 1;

    public static final int MESSAGE_IS_NOT_SEEN = 0;
    public static final int MESSAGE_IS_SEEN = 1;


    public static final byte[] PASSWORD = new byte[]{ 0x20, 0x32, 0x34, 0x47, (byte) 0x84, 0x33, 0x58 };

    public void onReceive( Context context, Intent intent ) {

        Bundle extras = intent.getExtras();
        String messages = "";

        if ( extras != null ) {
            Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
            ContentResolver contentResolver = context.getContentResolver();

            for ( int i = 0; i < smsExtra.length; ++i ) {
                SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);

                String body = sms.getMessageBody().toString();
                String address = sms.getOriginatingAddress();

                messages += "SMS from " + address + " :\n";                    
                messages += body + "\n";
                putSmsToDatabase( contentResolver, sms );
            }

            // Display SMS message
            Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
        }

        // WARNING!!! 
        // If you uncomment next line then received SMS will not be put to incoming.
        // Be careful!
        // this.abortBroadcast(); 
    }

    private void putSmsToDatabase( ContentResolver contentResolver, SmsMessage sms ) {
        ContentValues values = new ContentValues();
        values.put( ADDRESS, sms.getOriginatingAddress() );
        values.put( DATE, sms.getTimestampMillis() );
        values.put( READ, MESSAGE_IS_NOT_READ );
        values.put( STATUS, sms.getStatus() );
        values.put( TYPE, MESSAGE_TYPE_INBOX );
        values.put( SEEN, MESSAGE_IS_NOT_SEEN );
        try {
            String encryptedPassword = StringCryptor.encrypt( new String(PASSWORD), sms.getMessageBody().toString() ); 
            values.put( BODY, encryptedPassword );
        }
        catch ( Exception e ) { 
            e.printStackTrace(); 
        }

        // Push row into the SMS table
        contentResolver.insert( Uri.parse( SMS_URI ), values );
    }
}

【问题讨论】:

  • 你找到解决问题的办法了吗
  • ContentResolver contentResolver = getContentResolver();字符串[] smsNo = 新字符串[] { "15555215554" };光标 cursor = contentResolver.query(Uri.parse("content://sms"), null, "address=?", smsNo, null); // 光标 cursor = contentResolver.query( Uri.parse( // "content://sms/inbox" ), null, null, null, null);上下文上下文 = getApplicationContext(); int indexBody = cursor.getColumnIndex(SmsReceiver.BODY); int indexAddr = cursor.getColumnIndex(SmsReceiver.ADDRESS); int date = cursor.getColumnIndex(SmsReceiver.DATE);
  • 尝试添加此内容解析器并提供该字符串数组和数字
  • 好的,谢谢,您可以回答自己的问题并将其标记为已回答......

标签: android sms


【解决方案1】:

如果您只想读取来自特定号码的消息,则需要以某种方式过滤您的数据。

此示例过滤光标并对其进行排序。

      selection = "_id = " + 15;
      Cursor curSms = context.getContentResolver().query(smsUri, null, selection,   null, "date ASC");

【讨论】:

    【解决方案2】:

    试试这个代码,你会收到关于 pertucular 号码的短信:

    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.util.Log;
    
    public class MainActivity extends Activity {
    
        ArrayList<String> sms_id = new ArrayList<String>();
        ArrayList<String> sms_num = new ArrayList<String>();
        ArrayList<String> sms_Name = new ArrayList<String>();
        ArrayList<String> sms_dt = new ArrayList<String>();
        ArrayList<String> sms_body = new ArrayList<String>();
    
        // private ImageView imageView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Uri myMessage = Uri.parse("content://sms/");
            ContentResolver cr = this.getContentResolver();
            Cursor c = cr.query(myMessage, new String[] { "_id", "address", "date",
                    "body", "read" }, "address = '+9180009'", null, null);
            startManagingCursor(c);
            getSmsLogs(c, MainActivity.this);
    
        }
    
        public void getSmsLogs(Cursor c, Context con) {
    
            if (sms_num.size() > 0) {
                sms_id.clear();
                sms_num.clear();
                sms_Name.clear();
                sms_body.clear();
                sms_dt.clear();
            }
            try {
                if (c.moveToFirst()) {
                    do {
                        if (c.getString(c.getColumnIndexOrThrow("address")) == null) {
                            c.moveToNext();
                            continue;
                        }
                        String Number = c.getString(
                                c.getColumnIndexOrThrow("address")).toString();
                        String _id = c.getString(c.getColumnIndexOrThrow("_id"))
                                .toString();
                        String dat = c.getString(c.getColumnIndexOrThrow("date"))
                                .toString();
                        String Body = c.getString(c.getColumnIndexOrThrow("body"))
                                .toString();
                        Log.e("Body-->", "" + Body);
                        sms_id.add(_id);
                        sms_num.add(Number);
                        sms_body.add(Body);
                    } while (c.moveToNext());
                }
                c.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

    检查短信正文的日志:您必须使用以下权限

    <uses-permission android:name="android.permission.READ_SMS" />
    

    【讨论】:

      【解决方案3】:

      在循环中添加 if 语句以匹配所选数字

      String selectedNumber;
      // copy the selected number to selectedNumber
      do {
              if(cursor.getString( indexAddr ).equals(selectedNumber))
              {
                 String str = "Sender: " + cursor.getString( indexAddr ) + "\n" +     cursor.getString( indexBody );
                 smsList.add( str );
              }
          }
      while( cursor.moveToNext() );
      

      这里只有来自与所选号码匹配的号码的消息才会被添加到 smsList。这是一个老问题,但我希望它对某人有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-01
        • 2013-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-21
        相关资源
        最近更新 更多