3

I am new to android development.I am developing small android application. In my application I want to retrieve newly coming sms and display this message to user. My code looks like

// HellowordActivity.java
package com.example.helloword;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class HellowordActivity extends BroadcastReceiver
{
    public void onReceive(Context context, Intent intent)
    {
    Bundle myBundle = intent.getExtras();
    SmsMessage [] messages = null;
    String strMessage = "";

    if (myBundle != null)
    {
        Object [] pdus = (Object[]) myBundle.get("pdus");
        messages = new SmsMessage[pdus.length];

        for (int i = 0; i < messages.length; i++)
        {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            strMessage += "SMS From: " + messages[i].getOriginatingAddress();
            strMessage += " : ";
            strMessage += messages[i].getMessageBody().toString();
            strMessage += "\n";
        }
         // Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();

        Intent _intent = new Intent(context, PopupActivity.class);
        _intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        _intent.putExtra("strMessage", strMessage);
        startActivity(_intent);
       }
    }

  }  

I added receiver and permission in Android Manifest.xml

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

      <receiver android:name=".HellowordActivity" >
                <intent-filter > 
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/> 
                </intent-filter> 
        </receiver> 
<activity android:name=".PopupActivity" android:launchMode="singleTop" />

I am not doing any thing in layout part.What I want as an output when new message will come; message text display to user with simple popup. Need Help.. Thank you...

nilkash
  • 7,408
  • 32
  • 99
  • 176
  • I installed this application on my android device. When new message arrives it not showing the message text(message body) i.e. in my code strMessage. I want to display that message to user...Any suggestion..... – nilkash Jul 03 '12 at 07:31

2 Answers2

12

Try this it works for me you will get a toast shown to you with the content of the message received:

package com.example.a;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

    public class SMSBroadcastReceiver extends BroadcastReceiver {

            private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
            private static final String TAG = "SMSBroadcastReceiver";

            @Override
            public void onReceive(Context context, Intent intent) {
                 Log.i(TAG, "Intent recieved: " + intent.getAction());

                    if (intent.getAction().equals(SMS_RECEIVED)) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            Object[] pdus = (Object[])bundle.get("pdus");
                            final SmsMessage[] messages = new SmsMessage[pdus.length];
                            for (int i = 0; i < pdus.length; i++) {
                                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                            }
                            if (messages.length > -1) {
                                Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
                            }
                        }
                    }
               }
        }

The AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.a"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.HARDWARE_TEST"/>


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <receiver android:name=".SMSBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" >
                </action>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Use DDMS to send sms to your emulator via Telnet

K_Anas
  • 31,226
  • 9
  • 68
  • 81
  • Thank you K_anas for reply. I will try it. – nilkash Jul 03 '12 at 08:28
  • @nilkash it works for me i can't add a snapshot because it happen to fast that i can't take snapshot on emulator – K_Anas Jul 03 '12 at 08:58
  • Thank you K_Anas.. It's working fine as required. And Thank you for your DDMS tip as well. – nilkash Jul 03 '12 at 08:58
  • @nilkash you are welcome, mark the answer as accepted to help others to know solution for such approach – K_Anas Jul 03 '12 at 09:00
  • @K_Anas : The broadcast recevier is triggered for every incling message, right? Then why are we looping for multiple messages in the receiver (the message[i])? – Ashwin Jul 01 '13 at 19:16
  • @Ashwin When we are receiving an sms message in BroadcastReceiver, we initially receive it as an array of PDUs!! – K_Anas Jul 02 '13 at 22:09
  • @K_Anas The Google administrators for the Google Play Store consider the RECEIVE_SMS permission (in the tutorial you mention) to be dangerous. As a result, an app that contains the permission will be rejected. Then the developer has to submit a form to Google Play administrators for approval. Other developers have mentioned the process is awful with feedback taking weeks and receiving outright rejections with either no explanations or generic feedback. Any ideas on how to avoid? – AJW Jul 15 '20 at 15:18
1

if you want to show an popup when SMS is Recived then you will need to Create an Activity with android:launchMode="singleTop" as:

In manifast declare Activity as:

<activity android:name=".PopupActivity" android:launchMode="singleTop" />

From HellowordActivity BroadcastReceiver start Activity as:

Intent intent = new Intent(context, PopupActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent .putExtra("strMessage", strMessage);
context.startActivity(intent);

And in your PopupActivity.class:

public class PopupActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
        Intent intent= getIntent();//get message here
        String strMessage = intent.getStringExtra("strMessage");
        //NOW YOU CAN SHOW THIS MESSAGE IN POPUP
    }
    @Override
    protected void onStop() {
        super.onStop();
        this.finish();
        // The activity is no longer visible (it is now "stopped")
    }

You can also checkout these Smspopup apps source code:

android-smspopup

sms-enhancer

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • see my edit answer every SMS popup app doing in same way as i told u – ρяσѕρєя K Jul 03 '12 at 07:39
  • try strMessage += `messages[i].getMessageBody().toString();` instead of `strMessage += messages[i].getMessageBody();` – ρяσѕρєя K Jul 03 '12 at 07:48
  • Thank you Imran for quick reply. As you said I create an activity. Declare activity in manifast and define activity in PopupActivity.java.But when I tried to start activity from HellowordActivity it gives me error for startActivity(intent) Error: method startActivity(intent) Undefine for the type of HellowordActivity – nilkash Jul 03 '12 at 08:25
  • @nilkash : plz edit your post with latest code and manifast xml – ρяσѕρєя K Jul 03 '12 at 08:27
  • Hye Imran Its working fine. But It triggers that activity and opens my application with blank window. I don't want to open my application. I just want to show simple popup(on home screen of device). Thank you for your your valuable help... – nilkash Jul 03 '12 at 08:54
  • @nilkash : just set Activity background transparent and make a 150*150 layout in the middle of Activity with any color – ρяσѕρєя K Jul 03 '12 at 08:57
  • @nilkash : i have also edit two source code links you can also check these apps he is doing same as i told u. because toast message appear for very short time and you are not able to get Click from Toast.Thanks so Much Dear Freind !!! :) – ρяσѕρєя K Jul 03 '12 at 09:02
  • Imran thank you. It's working fine.Great work.I accept K_Anas's ans Because it gives me output exactly what I need.Your solution also working fine.... – nilkash Jul 03 '12 at 09:03