How to use Broadcast Receiver in Android – Send and Receive SMS

Sending SMS is one of the basic features every phone has. In this tutorial we’ll create a SMS Sending Application for Android. You app can also Intercept any incoming SMS and perform task based on pre-defined rules, we’ll use Broadcast receiver for the listening  purpose and write a working code.

Project Name: HelloSMS
Android Level: Android 2.3.3
Application Name: HelloSMS
Package Name: com.vineetdhanawat.hellosms
Create Activity: HelloSMS
Min SDK Version: 10
 

Layout

We’ll start with creating a layout for our main screen.

Components

  • 2 Text Strings
  • 2 Editable Text Box
  • Character Counter in Message
  • Send Button
Send-SMS

The Home Screen of the SendSMS App

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Enter the phone number of the recipient"
 />
<EditText
 android:id="@+id/phoneNo"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
/>
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Message"
/>
<EditText
 android:id="@+id/textMessage"
 android:layout_width="fill_parent"
 android:layout_height="160px"
 android:gravity="top"
/>
<TextView
 android:id="@+id/counter"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="160/0"
/>
<Button
 android:id="@+id/sendSMS"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Send SMS"
/>
</LinearLayout>

HelloSMS Main Activity

In the Main HelloSMS Activity, we’ll do 2 things.

  • Bind the Send SMS button to a OnClickListener() for sending sms.
  • Bind the Message Text box to addTextChangedListener() for counter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.vineetdhanawat.hellosms;
 
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class HelloSMS extends Activity {
 // Called when the activity is first created.
  Button sendSMS;
  EditText phoneNo;
  EditText textMessage;
  TextView mCounter;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    sendSMS = (Button) findViewById(R.id.sendSMS);
    phoneNo = (EditText) findViewById(R.id.phoneNo);
    textMessage = (EditText) findViewById(R.id.textMessage);
    mCounter = (TextView) findViewById(R.id.counter);
 
    textMessage.addTextChangedListener(mTextEditorWatcher);
 
    // On Click Listener on the sendSMS Button.
    sendSMS.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        String mobNo = phoneNo.getText().toString();
        String message = textMessage.getText().toString();
        if (mobNo.length()>0 && message.length()>0)
          sendSMS(mobNo, message);
        else
          Toast.makeText(getBaseContext(),
          "Please enter both phone number and message.",
          Toast.LENGTH_SHORT).show();
      }
    });
  }
}

The sendSMS() is defined as follows: We do not need to instantiate this class directly, Instead we can call getdefault() to obtain the SmsManager Object. sendTextMessage() send the sms with a PendingIntent. In this case it does nothing, but it can be used to monitor the status of sent SMS.

1
2
3
4
5
6
7
8
// Method to send SMS.
private void sendSMS(String phoneNumber, String message)
{
  PendingIntent pi = PendingIntent.getActivity(this, 0,
    new Intent(this, SMS.class), 0);
  SmsManager sms = SmsManager.getDefault();
  sms.sendTextMessage(phoneNumber, null, message, pi, null);
}

Let us modify the code to monitor the Sent / Delivered status of the SMS. We’ll need to use BroadcastReceiver object for the purpose.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Method to send SMS.
private void sendSMS(String mobNo, String message) {
  String smsSent = "SMS_SENT";
  String smsDelivered = "SMS_DELIVERED";
  PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
     new Intent(smsSent), 0);
  PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
     new Intent(smsDelivered), 0);
 
  // Receiver for Sent SMS.
  registerReceiver(new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent arg1) {
      switch (getResultCode())
      {
        case Activity.RESULT_OK:
          Toast.makeText(getBaseContext(), "SMS sent",
            Toast.LENGTH_SHORT).show();
          break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
          Toast.makeText(getBaseContext(), "Generic failure",
            Toast.LENGTH_SHORT).show();
          break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
          Toast.makeText(getBaseContext(), "No service",
            Toast.LENGTH_SHORT).show();
          break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
          Toast.makeText(getBaseContext(), "Null PDU",
            Toast.LENGTH_SHORT).show();
          break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
          Toast.makeText(getBaseContext(), "Radio off",
            Toast.LENGTH_SHORT).show();
          break;
      }
    }
  }, new IntentFilter(smsSent));
 
  // Receiver for Delivered SMS.
  registerReceiver(new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent arg1) {
      switch (getResultCode())
      {
        case Activity.RESULT_OK:
          Toast.makeText(getBaseContext(), "SMS delivered",
            Toast.LENGTH_SHORT).show();
          break;
        case Activity.RESULT_CANCELED:
          Toast.makeText(getBaseContext(), "SMS not delivered",
            Toast.LENGTH_SHORT).show();
          break;
        }
      }
    }, new IntentFilter(smsDelivered));
 
  SmsManager sms = SmsManager.getDefault();
  sms.sendTextMessage(mobNo, null, message, sentPI, deliveredPI);
}

Let us now implement the addTextChangedListener() as Counter.

SMS-Counter

Counter Display = No of Chars Left / Required SMS Count

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private final TextWatcher mTextEditorWatcher = new TextWatcher() {
  public void beforeTextChanged(CharSequence s, int start,
   int count, int after) {
  }
  public void onTextChanged(CharSequence s, int start,
   int before, int count) {
    //This sets a textview to the current length
    String smsNo;
    if(s.length() == 0)
      smsNo = "0";
    else
    smsNo = String.valueOf(s.length()/160 + 1);
    String smsLength = String.valueOf(160-(s.length()%160));
    mCounter.setText(smsLength+"/"+smsNo);
  }
  @Override
  public void afterTextChanged(Editable arg0) {
    // TODO Auto-generated method stub
  }
};

Permissions

In the AndroidManifest.xml file, we need to add the two permissions SEND_SMS and RECEIVE_SMS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="utf-8"?>
    package="com.vineetdhanawat.hellosms"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="10" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".HelloSMS"
            android:label="@string/app_name" >
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

Broadcast Receiver (Intercepting SMS)

Applications can intercept Incoming SMS as well. To do so, you need to add <receiver> element inside AndroidManifest.xml . Make sure it is included inside element.

1
2
3
4
5
6
<receiver android:name="com.vineetdhanawat.hellosms.SMSReceiver"
  android:enabled="true">
  <intent-filter>
  <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

Add a new Class file SMSReceiver.java. Here we’ll be parsing the intercepted sms and displaying as Toast. But this will Toast all the incoming sms. In case you want to Toast particular senders, use getOriginatingAddress();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.vineetdhanawat.hellosms;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
 
public class SMSReceiver extends BroadcastReceiver {
 
    @Override
    public void onReceive(Context context, Intent intent) {
        // Parse the SMS.
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            // Retrieve the SMS.
            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]);
                // In case of a particular App / Service.
                //if(msgs[i].getOriginatingAddress().equals("+91XXX"))
                //{
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "n";
                //}
            }
            // Display the SMS as Toast.
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }
    }
}

That’s it. You can also use two emulators, By default they will have device names as emulator-5554 and emulator-5556. You can test it by sending sms from one of them to another giving emulator-5556 or just 5556 as the number.

App Ideas?

Using the Location Sensing (GPS) post which i posted a while before, and Broadcast Receiver above, It opens up a whole lot possibility of Apps.

Apps like JustDial. Where you have a lot of options like Theatres, Restaurant etc. All you need to do is choose an option. The app detects your location and sends your location to a pre-defined no. The server responds with list of available results (Say nearest Restaurants).

Want to learn more about Android Service and Broadcast Receiver? Check out Vogel’s Blog

Do you have any other Interesting App Ideas? Do share with us in the comments!

 

[출처] http://www.vineetdhanawat.com/blog/2012/04/how-to-use-broadcast-receiver-in-android-send-and-receive-sms/

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
47 [Android SDK] 동기와 비동기 처리의 이해 및 안드로이드에서의 적용 file 졸리운_곰 2024.05.01 120
46 [Android SDK] [Android] 안드로이드에서 Delay 구현 - Thread 졸리운_곰 2024.05.01 99
45 [Android SDK] How to implement Do nothing for a certain period of time in Android 졸리운_곰 2024.05.01 134
44 [Android SDK] Android handle을 이용한 지연처리: postDelayed 등 졸리운_곰 2024.05.01 132
43 [Android SDK] [안드로이드 스튜디오] 로딩창 구현 (ProgressBar) file 졸리운_곰 2024.05.01 126
42 [Android SDK] [Android] 안드로이드 Alert 창 띄우기 file 졸리운_곰 2024.05.01 124
41 [Android SDK] Android thread에서 Toast 호출하기 file 졸리운_곰 2024.05.01 88
40 [Android SDK] runOnUiThread란? (개념과 사용법) file 졸리운_곰 2024.05.01 165
39 [Android SDK] How to enable/disable WiFi from an application? 안드로이드 와이파이 켜고 끄기 java 졸리운_곰 2024.05.01 138
38 [Android SDK] 안드로이드 화면꺼짐 방지 코드 졸리운_곰 2024.05.01 108
37 Android WebView javascriptInterface 사용하기 file 졸리운_곰 2018.03.26 656
36 안드로이드 에서 JSON 읽어오기 (JSON parser) file 가을의곰 2017.06.18 827
35 Android Basic JSOUP Tutorial file 졸리운_곰 2017.03.27 349
34 [Android] 안드로이드 웹페이지 파싱하기 - jsoup 이용하기 file 졸리운_곰 2017.03.27 724
33 Android에서 jsoup를이용하여 HTML 파서(Parser) file 졸리운_곰 2017.03.27 764
32 윈도우즈에서 IntelliJ IDEA + android 개발환경 만들기 file 졸리운_곰 2016.12.05 488
31 단말기 내부에 폴더 및 txt파일 생성하기 file 졸리운_곰 2016.05.01 171
30 wifi 연결시 알림 android source 졸리운_곰 2016.05.01 250
» How to use Broadcast Receiver in Android – Send and Receive SMS file 졸리운_곰 2016.05.01 292
28 [Android] Layout XML - layout_weight file 졸리운_곰 2016.04.30 23630
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED