我扩展广播接收器:
public class MyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (null == bundle)
return;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
int a = 2;
if (currentTimeString.length() == 5) {
a = 3;
}
String minutes = currentTimeString.substring(a);
if (phoneNumber.equals(minutes)) {
//some code
}
}
}
我的一位用户使用 ACRA 收到了以下崩溃报告(因此,我不能重复此错误):
"java.lang.RuntimeException: Unable to start receiver myapp.service.MyBroadcast: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2144)
at android.app.ActivityThread.access$2400(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1114)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4389)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at myapp.service.MyBroadcast.onReceive(MyBroadcast.java:31)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2103)
... 10 more
java.lang.NullPointerException
at myapp.service.MyBroadcast.onReceive(MyBroadcast.java:31)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2103)
at android.app.ActivityThread.access$2400(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1114)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4389)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
at dalvik.system.NativeStart.main(Native Method)"
所以,第 31 行有 NullPointerException:
if (phoneNumber.equals(minutes)) {
据我了解字符串之一phoneNumber
或minutes
为空。而且我认为intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)
在我的情况下不能为空(或者我错了?)。我假设它currentTimeString
的长度为 4 或 5 个符号(例如,因为它返回 1:45 或 20:54)。也许原因是遇到此错误的用户具有语言环境 en_PK(我认为是巴基斯坦)并DateFormat.getTimeInstance
以某种奇怪的格式返回时间,但正如我所见,应该没有什么奇怪的......
这是什么原因造成的NullPointerException
?