【发布时间】:2021-05-11 18:01:29
【问题描述】:
package com.example.helloworld;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import java.util.Locale;
public class IncomingCallBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = "PHONE STATE";
private static String mLastState;
private final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void onReceive(final Context context, Intent intent) {
Log.d(TAG,"onReceive()");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(mLastState)) {
return;
} else {
mLastState = state;
}
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (incomingNumber == null ) {
Log.i("call-state", " : NULL");
} else {
if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
Toast.makeText(context, "call Active", Toast.LENGTH_SHORT).show();
} else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
Toast.makeText(context, "No call", Toast.LENGTH_SHORT).show();
} else if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
Toast.makeText(context, "Ringing State", Toast.LENGTH_SHORT).show();
Toast.makeText(context, incomingNumber, Toast.LENGTH_SHORT).show();
}
}
final String phone_number;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
phone_number = PhoneNumberUtils.formatNumber(incomingNumber, Locale.getDefault().getCountry());
} else {
phone_number = PhoneNumberUtils.formatNumber(incomingNumber);
}
Intent serviceIntent = new Intent(context, CallingService.class);
serviceIntent.putExtra(CallingService.EXTRA_CALL_NUMBER, phone_number);
context.startService(serviceIntent);
}
}
}
我检查并尝试了所有 stackoverflow 问题和答案。 但是,程序会在以下位置引发异常:
phone_number = PhoneNumberUtils.formatNumber(incomingNumber, Locale.getDefault().getCountry());
这是个例外:
java.lang.RuntimeException: 无法启动接收器 com.example.helloworld.IncomingCallBroadcastReceiver: java.lang.NullPointerException:尝试调用虚拟方法 'boolean java.lang.String.startsWith(java.lang.String)' 为空 对象引用
因此,我猜以下是返回 null:
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
我尝试了许多其他方法,例如添加READ_CALL_LOG。但它没有用。
连吐司消息都没有显示。
有什么办法解决吗?
【问题讨论】:
-
别猜了,看看什么是空的。例如使用调试器或通过记录一些值。找出问题所在是解决问题的第一步。
-
显而易见的问题是:您使用的是什么 API/权限/设备?由于 API 29 不推荐使用 telephonyManager
-
@ibecar 我正在使用 API 28
-
@Henry 我检查了它,它返回 null!
标签: java android-studio nullpointerexception telephonymanager