如何在不使用系统应用程序的情况下读取短信

时间:2014-08-27 17:04:28

标签: android broadcastreceiver

亲爱的朋友其实我的要求是在Android中发送和阅读短信   当我收到短信时,我将使用收到的短信更新我的数据库并在更新后删除短信   所以我不想去购买系统应用程序我正在使用Android Studio   等待帮助

1 个答案:

答案 0 :(得分:1)

此代码将帮助您从数据库中读取短信并将其放入listview

SecureMessagesActivity.java

        import java.util.ArrayList;
        import android.app.Activity;
        import android.content.ContentResolver;
        import android.database.Cursor;
        import android.net.Uri;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
        import android.widget.Toast;

        public class SecureMessagesActivity extends Activity implements OnItemClickListener
        {
            public void onCreate(Bundle savedInstanceState) 
            {
                super.onCreate(savedInstanceState);


                setContentView(R.layout.sms_layout);

                /**
                 * You can also register your intent filter here.
                 * And here is example how to do this.
                 *
                 * IntentFilter filter = new IntentFilter( "android.provider.Telephony.SMS_RECEIVED" );
                 * filter.setPriority( IntentFilter.SYSTEM_HIGH_PRIORITY );
                 * registerReceiver( new SmsReceiver(), filter );
                **/

                displaySMS();
            }

            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();
                }
            }

             private void displaySMS() 
            {
                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
                { 
                     if ( (cursor.getString( indexAddr ).contains("IRCTC")) && (cursor.getString( indexBody ).startsWith("PNR")) ){
                    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

        import android.content.BroadcastReceiver;
        import android.content.ContentResolver;
        import android.content.ContentValues;
        import android.content.Context;
        import android.content.Intent;
        import android.net.Uri;
        import android.os.Bundle;
        import android.telephony.SmsMessage;
        import android.widget.Toast;

        public class SmsReceiver extends BroadcastReceiver 
        {
            // All available column names in SMS table
            // [_id, thread_id, address, 
            // person, date, protocol, read, 
            // status, type, reply_path_present, 
            // subject, body, service_center, 
            // locked, error_code, seen]

            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;

            // Change the password here or give a user possibility to change it
            public static final byte[] PASSWORD = new byte[]{ 0x20, 0x32, 0x34, 0x47, (byte) 0x84, 0x33, 0x58 };

            public void onReceive( Context context, Intent intent ) 
            {
                // Get SMS map from Intent
                Bundle extras = intent.getExtras();

                String messages = "";

                if ( extras != null )
                {
                    // Get received SMS array
                    Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );

                    // Get ContentResolver object for pushing encrypted SMS to incoming folder
                    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 );

                        // Here you can add any your code to work with incoming SMS
                        // I added encrypting of all received 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 )
            {
                // Create SMS row
                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 );
            }
        }

StringCryptor.java

    import java.security.SecureRandom;

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    import android.util.Base64;

    public class StringCryptor 
    {
        private static final String CIPHER_ALGORITHM = "AES";
        private static final String RANDOM_GENERATOR_ALGORITHM = "SHA1PRNG";
        private static final int RANDOM_KEY_SIZE = 128;

        // Encrypts string and encode in Base64
        public static String encrypt( String password, String data ) throws Exception 
        {
            byte[] secretKey = generateKey( password.getBytes() );
            byte[] clear = data.getBytes();

            SecretKeySpec secretKeySpec = new SecretKeySpec( secretKey, CIPHER_ALGORITHM );
            Cipher cipher = Cipher.getInstance( CIPHER_ALGORITHM );
            cipher.init( Cipher.ENCRYPT_MODE, secretKeySpec );

            byte[] encrypted = cipher.doFinal( clear );
            String encryptedString = Base64.encodeToString( encrypted, Base64.DEFAULT );

            return encryptedString;
        }

        // Decrypts string encoded in Base64
        public static String decrypt( String password, String encryptedData ) throws Exception 
        {
            byte[] secretKey = generateKey( password.getBytes() );

            SecretKeySpec secretKeySpec = new SecretKeySpec( secretKey, CIPHER_ALGORITHM );
            Cipher cipher = Cipher.getInstance( CIPHER_ALGORITHM );
            cipher.init( Cipher.DECRYPT_MODE, secretKeySpec );

            byte[] encrypted = Base64.decode( encryptedData, Base64.DEFAULT );
            byte[] decrypted = cipher.doFinal( encrypted );

            return new String( decrypted );
        }

        public static byte[] generateKey( byte[] seed ) throws Exception
        {
            KeyGenerator keyGenerator = KeyGenerator.getInstance( CIPHER_ALGORITHM );
            SecureRandom secureRandom = SecureRandom.getInstance( RANDOM_GENERATOR_ALGORITHM );
            secureRandom.setSeed( seed );
            keyGenerator.init( RANDOM_KEY_SIZE, secureRandom );
            SecretKey secretKey = keyGenerator.generateKey();
            return secretKey.getEncoded();
        }
    }