안드로이드 BroadcastReceiver
Android 2015. 2. 26. 17:59broadcast ; 방송하다
receiver; 수신자
말 그대로 안드로이드의 여러 이벤트들을 받아 처리해주는 클래스.
BroadcastReceiver를 상속받아 onReceive 메소드를 오버라이드하여 해당 이벤트를 처리한다.
custom intent를 만들어 BroadcastReceiver를 테스트 해보면...
1. BroadcastReceiver를 상속받은 클래스를 선언한다.
이 클래스에서 발생되는 이벤트에 따라 처리함.
package com.example.testproject;
import android.content.BroadcastReceiver;
..
public class TestReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
2. AndroidManifest에 receiver로서 선언.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="com.tutorial.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
3. MainActivity에서 custom intent 발생시키고 테스트를 하면..
package com.example.testproject;
import android.app.Activity;
..
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
Button btn1 = new Button(this);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
btn1.setLayoutParams(params);
btn1.setText("Broadcast Test");
container.addView(btn1);
btn1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 버튼이 눌리면 custom intent를 보냄
Intent intent = new Intent();
intent.setAction("com.tutorial.CUSTOM_INTENT");
sendBroadcast(intent);
}
});
}
}
위의 단계로 예제를 작성하고 실행해보면 intent가 보내지면 TestReceiver에서 이벤트 발생을 감지하고 메세지를 보여준다.
단점.
위는 정적Receiver로서 Receiver를 사용할 일이 없어질 경우에 해제가 어렵다.
http://www.tutorialspoint.com/android/android_broadcast_receivers.htm
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#tutorial_receiver
receiver를 동적으로 생성하려면 component 안에 동적으로 선언하며,
component의 생명주기를 따른다.
http://newtoynt.tistory.com/entry/Broadcast-Receiver%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C-%ED%8E%8C