통화 수신 시 동작을 처리하는 클래스입니다.
public class CallReceiver extends BroadcastReceiver {
private String previousState = "";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state != null && !state.equals(previousState)) {
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
handleRingingCall(context, intent);
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
handleActiveCall(context, intent);
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
handleIdleCall(context, intent);
}
previousState = state;
}
}
}
private void handleRingingCall(Context context, Intent intent) {
String phone = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (phone != null) {
System.out.println("통화 수신 확인");
// 수신 번호 가져옴
phoneNumtoReport = phone;
}
}
private void handleActiveCall(Context context,Intent intent) {
String phone = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (phone != null) {
System.out.println("통화 중 확인");
}
}
private void handleIdleCall(Context context, Intent intent) {
String phone = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (phone != null) {
System.out.println("통화 종료 확인");
phoneNumtoReport = phone;
}
}
}
Manifest 파일에 다음 코드를 추가하여 완성합니다.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<application
<receiver
android:name=".CallReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>