gpt4 book ai didi

Android空指针异常

转载 作者:行者123 更新时间:2023-11-29 00:44:42 26 4
gpt4 key购买 nike

简而言之...我有一个小部件,您可以在下面看到重要的部分

public class ExampleWidget extends AppWidgetProvider {
private PhoneStateListener listener;
private TelephonyManager telephonyManager;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {

listener = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state) {
// removed the code
}

};

telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(listener,
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

}

@Override
public void onDisabled(Context context) {
telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
super.onDisabled(context);
}
}

当我从主屏幕上删除小部件时,我在 telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE); 处收到空指针异常。

我错过了什么?

最佳答案

context.getSystemService() 可能会返回 null,如果 telephonyManagernull,则您无法证明它。如果 Context.TELEPHONY_SERVICE 标识的名称在系统中不存在,则 telephonyManager 将为 null

除了您的评论:

@Override
public void onDisabled(Context context) {
if (telephonyManager!=null){
telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
}
super.onDisabled(context);
}

如果您需要在 onDisabled 方法中运行此代码,您应该初始化 telephonyManager。它闻起来像 onDisabled 方法在 onUpdate 之前以某种方式被调用,或者如果您有两个不同的实例。

关于Android空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6995619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com