简体   繁体   中英

Read the incoming sms and pass the message body to android application

I am developing an android application in which I want to read the sms and pass the data to my application.

I tried many ways but cant't figure it out. Here is what I am doing. Is something wrong in my code.

 String msg_body = "";
       Uri my_uri = Uri.parse("content://sms/inbox");
       Cursor readFstSms = v.getContext().getContentResolver().query(my_uri, null, null, null, null);
       if(readFstSms.moveToFirst())
       {
           msg_body = readFstSms.getString(readFstSms.getColumnIndexOrThrow("body")).toString();
       }
       readFstSms.close();
       Uri gmmIntentUri = Uri.parse("google.navigation:q=" + msg_body);
       Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
       mapIntent.setPackage("com.google.android.apps.maps");
       startActivity(mapIntent);

I also added <uses-permission android:name="android.permission.READ_SMS"/> in my manifest file but still can't find the solution

First of all you need to set the read permissions for the app through manifest

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

And you need a BroadcastReciever which should be declared in manifest with the intent filter android.provider.Telephony.SMS_RECEIVED '
Once the reciever starts working, You can handle the recieved SMS in the onRecieve callback method of that BroadcastReceiver.

if (intentExtras != null) {
            Object[] messages = (Object[]) intentExtras.get(SMS_BUNDLE);

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

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

 Toast.makeText(context, body, Toast.LENGTH_SHORT).show();

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM