마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

브로드캐스트의 context에관해 궁금한게 있습니다.

0 추천

브로드 캐스트를 공부중인데, context에 의문이 들어서

context에대해 굉장히많이 찾아봤는데 긴가민가 해서 질문드립니다!

public class SmsReceiver extends BroadcastReceiver {

    public static final String TAG = "SmsReceiver";
    public SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "onReceive() 호출");

        Bundle bundle = intent.getExtras();
        SmsMessage[] messages = parseSmsMessage(bundle);

        if(messages!=null&&messages.length>0){
            String sender=messages[0].getOriginatingAddress();
            Log.i(TAG, "SMS sender : " + sender);

            String contents=messages[0].getMessageBody().toString();
            Log.i(TAG, "SMS contents : " + contents);

            Date receivedDate=new Date(messages[0].getTimestampMillis());
            Log.i(TAG, "SMS received date : " + receivedDate.toString());

            sendToActivity(context,sender, contents, receivedDate);
        }
    }

    private void sendToActivity(Context context,String sender,String contents,Date receivedDate){
        Intent myIntent=new Intent(context,SmsActivity.class);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        myIntent.putExtra("sender",sender);
        myIntent.putExtra("contents",contents);
        myIntent.putExtra("receivedDate",format.format(receivedDate));
        context.startActivity(myIntent);
    }

일부만 떼어 왔는데, 저기 인텐트를 보내는 부분에서 리시버 클래스 this를 선언하지 못하는 이유를 찾아봤는

데, "브로드캐스트 리시버는 다른 서비스,액티비티등과 달리 자기자신이 context가 될수없기때문에

onReceive에 전달되는 context를 이용한다." 라고 이해했는데 제가 맞게 이해하고 있는걸까요?

익명사용자 님이 2019년 1월 11일 질문

1개의 답변

0 추천

간단합니다.

서비스, 액티비티등은 Context를 '상속' 받아 구현되어 있기 때문에 this 자체가 Context처럼 사용할 수 있는겁니다.

브로드캐스트 리시버는 Context를 상속 받지 않습니다.

디자이너정 (42,810 포인트) 님이 2019년 1월 12일 답변
완벽히 이해가되었습니다!!!
감사합니다 ㅜㅜㅜ
...