웹사이트 검색

Android BroadcastReceiver 예제 자습서


오늘 우리는 Android Framework의 매우 중요한 구성 요소인 Android BroadcastReceiver에 대해 논의하고 구현할 것입니다.

안드로이드 브로드캐스트 리시버

Android BroadcastReceiver는 시스템 전체의 브로드캐스트 이벤트 또는 의도를 수신하는 Android의 휴면 구성요소입니다. 이러한 이벤트가 발생하면 상태 표시줄 알림을 생성하거나 작업을 수행하여 애플리케이션을 작동시킵니다. 활동과 달리 Android BroadcastReceiver에는 사용자 인터페이스가 없습니다. 브로드캐스트 리시버는 일반적으로 수신된 인텐트 데이터의 유형에 따라 작업을 서비스에 위임하도록 구현됩니다. 다음은 시스템 전체에서 생성된 중요한 의도 중 일부입니다.

  1. android.intent.action.BATTERY_LOW : 기기의 배터리 부족 상태를 나타냅니다.
  2. android.intent.action.BOOT_COMPLETED : 시스템 부팅이 완료된 후 한 번 방송됩니다.
  3. android.intent.action.CALL : 데이터로 지정된 사람에게 전화를 걸기 위해
  4. android.intent.action.DATE_CHANGED : 날짜가 변경되었습니다.
  5. android.intent.action.REBOOT : 기기 재부팅
  6. android.net.conn.CONNECTIVITY_CHANGE : 모바일 네트워크 또는 Wi-Fi 연결이 변경(또는 재설정)됨

Android의 브로드캐스트 수신기

Android 애플리케이션에서 Broadcast Receiver를 설정하려면 다음 두 가지 작업을 수행해야 합니다.

  1. BroadcastReceiver 만들기
  2. BroadcastReceiver 등록

BroadcastReceiver 만들기

아래와 같이 사용자 지정 BroadcastReceiver를 빠르게 구현해 보겠습니다.

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }
 
    @Override
    public void onReceive(Context context, Intent intent) {
      
        Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();
    }
}

BroadcastReceiver는 onReceiver() 메서드가 추상적인 추상 클래스입니다. onReceiver() 메서드는 이벤트가 발생할 때 등록된 Broadcast Receiver에서 먼저 호출됩니다. 의도 개체는 모든 추가 데이터와 함께 전달됩니다. Context 개체도 사용할 수 있으며 각각 context.startActivity(myIntent); 또는 context.startService(myService);를 사용하여 활동 또는 서비스를 시작하는 데 사용됩니다.

안드로이드 앱에 BroadcastReceiver 등록

BroadcastReceiver는 두 가지 방법으로 등록할 수 있습니다.

  1. 아래와 같이 AndroidManifest.xml 파일에 정의합니다.

<receiver android:name=".ConnectionReceiver" >
             <intent-filter>
                 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
             </intent-filter>
</receiver>

인텐트 필터를 사용하여 하위 요소와 일치하는 인텐트가 특정 broadcast receiver로 전달되어야 한다고 시스템에 알립니다.3. 프로그래밍 방식으로 정의하여

IntentFilter filter = new IntentFilter();
intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");
 
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);

활동의 onStop() 또는 onPause()에서 broadcast receiver를 등록 취소하려면 다음 스니펫을 사용할 수 있습니다.

@Override
protected void onPause() {
    unregisterReceiver(myReceiver);
    super.onPause();
}

활동에서 브로드캐스트 인텐트 보내기

다음 스니펫은 모든 관련 BroadcastReceivers에 인텐트를 보내는 데 사용됩니다.

Intent intent = new Intent();
      intent.setAction("com.journaldev.CUSTOM_INTENT");
      sendBroadcast(intent);

매니페스트의 인텐트 필터 태그에 또는 프로그래밍 방식으로 위 작업을 추가하는 것을 잊지 마세요. 네트워크 변경 이벤트와 사용자 지정 의도를 수신하고 그에 따라 데이터를 처리하는 애플리케이션을 개발해 보겠습니다.

Android 프로젝트 구조의 BroadcastReceiver

Android BroadcastReceiver 코드

activity_main.xml은 브로드캐스트 인텐트를 전송하는 중앙의 버튼으로 구성됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.journaldev.broadcastreceiver.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="Send Broadcast"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

MainActivity.java는 아래와 같습니다.

package com.journaldev.broadcastreceiver;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    ConnectionReceiver receiver;
    IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.inject(this);

        receiver = new ConnectionReceiver();
        intentFilter = new IntentFilter("com.journaldev.broadcastreceiver.SOME_ACTION");

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(receiver);
    }

    @OnClick(R.id.button)
    void someMethod() {

        Intent intent = new Intent("com.journaldev.broadcastreceiver.SOME_ACTION");
        sendBroadcast(intent);
    }
}

위의 코드에서 프로그래밍 방식으로 또 다른 사용자 지정 작업을 등록했습니다. ConnectionReceiver는 AndroidManifest.xml 파일에 아래와 같이 정의되어 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.journaldev.broadcastreceiver">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".ConnectionReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

ConnectionReceiver.java 클래스는 아래에 정의되어 있습니다.

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

        Log.d("API123",""+intent.getAction());

        if(intent.getAction().equals("com.journaldev.broadcastreceiver.SOME_ACTION"))
            Toast.makeText(context, "SOME_ACTION is received", Toast.LENGTH_LONG).show();

        else {
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();
            if (isConnected) {
                try {
                    Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(context, "Network is changed or reconnected", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Android BroadcastReceiver 프로젝트 다운로드