반응형
BroadcastReceiver
설명
- 디바이스에서 특정 이벤트가 발생했을 때에 대한 처리를 백그라운드로 수행하는 것.
- 안드로이드 8.0 이상부터는 대상 애플리케이션이 실행중일 경우에만 암시적 인텐트를 사용 가능, 그 외에는 불가능
- ex) 배터리 부족 이벤트 발생시 알림 토스트 발생시키기
기본 코드
manifests/AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_example">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Androidexample">
<receiver
android:name=".TestReceiver"
android:enabled="true"
android:exported="true" />
<activity android:name=".MainActivity">
<intent-filter>
<!-- Entry Point -->
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
TestReceiver
class TestReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "리시버 동작", Toast.LENGTH_SHORT).show()
}
}
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
/*
// 현재 애플리케이션의 BroadCastReceiver 실행
val intent = Intent(this, TestReceiver::class.java)
sendBroadcast(intent)
*/
// 다른 애플리케이션의 BroadCastReceiver 실행
val intent = Intent()
intent.setClassName("com.example.android_example", "com.example.android_example.TestReceiver")
sendBroadcast(intent)
}
}
}
Intent Filter 지정 코드
manifests/AndroidManifest.xml<receiver
android:name=".TestReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.test" />
</intent-filter>
</receiver>
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
// 다른 애플리케이션의 BroadCastReceiver 실행
val intent = Intent("com.test")
sendBroadcast(intent)
}
}
}
시스템 메시지 예제 코드
manifests/AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_example">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Androidexample">
<receiver
android:name=".TestReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<!-- Entry Point -->
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
TestReceiver
class TestReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED -> {
Toast.makeText(context, "부팅 완료", Toast.LENGTH_SHORT).show()
}
Telephony.Sms.Intents.SMS_RECEIVED_ACTION -> {
val bundle = intent.extras
if (bundle != null) {
val obj = bundle.get("pdus") as Array<*>
val msg = arrayOfNulls<SmsMessage>(obj.size)
for (i in obj.indices) {
msg[i] = SmsMessage.createFromPdu(obj[i] as ByteArray)
}
for (i in msg.indices) {
val message = "${msg[i]?.originatingAddress} : ${msg[i]?.messageBody}"
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
}
}
}
}
MainActivity
class MainActivity : AppCompatActivity() {
private val permissionList = arrayOf(
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.RECEIVE_SMS
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
checkPermission()
}
private fun checkPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return
}
for (permission : String in permissionList) {
val check = checkCallingOrSelfPermission(permission)
if (check == PackageManager.PERMISSION_DENIED) {
requestPermissions(permissionList, 0)
break
}
}
}
}
참고
반응형
'Development > Android' 카테고리의 다른 글
[Android] SQLite (0) | 2021.02.09 |
---|---|
[Android] Service (0) | 2021.02.09 |
[Android] Thread & Handler (0) | 2021.02.09 |
[Android] DialogFragment (0) | 2021.02.09 |
[Android] ListFragment (0) | 2021.02.09 |