본문 바로가기
안드로이드 자바

[Android][Java] 브로드캐스트리시버를 이용해 문자 수신 받기

by teamnova 2023. 3. 11.
728x90

안녕하세요 오늘은 브로드캐스트리시버를 이용해 수신받은 문자 내용을 한번 띄워보겠습니다.

 

먼저 브로드캐스트리시버 클래스를 작성해 줍니다.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        String number = "";
        Bundle bundle = intent.getExtras();
        //parsing message
        SmsMessage[] messages = parseMessage(bundle);

        if(messages.length > 0) {
            String sender = messages[0].getOriginatingAddress();
            String content = messages[0].getMessageBody().toString();
            sendToActivity(context, sender, content);

        }
    }

    private void sendToActivity(Context context, String sender, String content) {
            Intent intent = new Intent(context, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("sender", sender);
            intent.putExtra("content",content);
            context.startActivity(intent);
    }

    private SmsMessage[] parseMessage(Bundle bundle) {
        Object[] objs = (Object[]) bundle.get("pdus");
        SmsMessage[] messages = new SmsMessage[objs.length];

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

        return messages;
    }
}

다음은 메니페스트에 권한 추가를 해주고 리시버를 등록해 줍니다.

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

<receiver
            android:name=".SMSReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

리시버 태그는 애플리케이션 태그 안에 넣어주시면 됩니다.

 

다음은 xml 파일입니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:textSize="30dp"
        android:id="@+id/text_view"/>


</androidx.constraintlayout.widget.ConstraintLayout>

다음은 메인액티비티 클래스입니다.

public class MainActivity extends AppCompatActivity {
    TextView text_view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text_view = findViewById(R.id.text_view);
        requirePermission();
    }
    private void requirePermission(){
        String[] permissions = {Manifest.permission.RECEIVE_SMS};
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS);
        if(permissionCheck == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(this, permissions, 0);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String sender = intent.getStringExtra("sender");
        String content = intent.getStringExtra("content");
        text_view.setText(sender + "\n" + content);
    }

}