public void handleMessage(Message msg) { switch (msg.what) { case -1: //网络请求失败 Toast.makeText(getApplicationContext(), "网络请求失败,修改失败!", Toast.LENGTH_LONG).show(); break;
时间: 2024-01-14 15:02:47 浏览: 24
这段代码是在Android中Handler的handleMessage()方法中的一部分,用于处理不同的消息类型。在这段代码中,通过判断message对象的what属性的值,来确定接下来要执行的操作。如果what属性的值为-1,表示网络请求失败,则会通过Toast.makeText()方法显示一个提示信息,提示用户网络请求失败,修改失败。Toast是Android中一种简单的提示框架,通过该框架可以在屏幕上显示一条短暂的提示信息。在这里,Toast.makeText()方法用于创建一个Toast对象,并将提示信息的内容、显示时间等相关参数传递给该对象。最后,通过调用Toast对象的show()方法,将提示信息显示在屏幕上。该方法的第一个参数为上下文对象,第二个参数为提示信息的内容,第三个参数为提示信息显示的时间长度。
相关问题
代码解释 private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle; switch (msg.what){ case msgKey1: bundle =msg.getData(); textView.setText(bundle.getString(pingRes)); break; default: break; } } };
这段代码定义了一个私有的Handler类,并重写了它的handleMessage方法。在该方法中,根据msg传递过来的what值进行了不同的操作,当what等于msgKey1时,将msg中的数据通过Bundle获取并设置到textView中,否则不进行任何操作。
// 在安卓fragment中写了获取路线规划,代码如下: // BaiduNaviManagerFactory.getRoutePlanManager().routePlan(list, currentPrefer, bundle, handler); // private final Handler handler = new Handler(Looper.getMainLooper()) { // @Override // public void handleMessage(@NonNull Message msg) { // super.handleMessage(msg); // switch (msg.what) { // case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START: // mFlRetry.setVisibility(View.GONE); // mLayoutTab0.setSelected(false); // mLayoutTab1.setSelected(false); // mLayoutTab2.setSelected(false); // break; // case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS: // mFlRetry.setVisibility(View.GONE); // mRlButton.setVisibility(View.VISIBLE); // updateBtnText(currentPrefer); // new Thread(() -> initData()).start(); // break; // case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED: // mFlRetry.setVisibility(View.VISIBLE); // break; // default: // break; // } // } // }; // 以上代码中 路线规划成功 后执行了 initData()方法, 方法中获取了3Tab信息和路线详情 这是个耗时操作,如下代码: // BNRoutePlanInfos routePlaneInfos = BaiduNaviManagerFactory.getRoutePlanManager() .getRoutePlanInfo(); // 所以在handler中使用了Thread来开启一个子线程去执行,那么获取3Tab信息和路线详情的getRoutePlanInfo()可能为空吗? // 如果报空指针异常,应该怎么处理?请帮我修改一下以上问题
在handler中使用Thread来开启一个子线程去执行initData()方法是正确的做法,这样可以避免在主线程中执行耗时操作导致UI卡顿的问题。但是需要注意的是,在子线程中调用getRoutePlanInfo()方法可能会返回null,因为该方法的执行时间可能比较长,而子线程的执行速度可能比主线程快,所以有可能在getRoutePlanInfo()方法执行完成之前子线程已经继续执行了下一步操作。如果getRoutePlanInfo()返回null,那么在使用该对象时就会抛出NullPointerException异常。
为了避免这种情况,可以在getRoutePlanInfo()方法返回null时进行延时重试,直到获取到非null的结果为止。具体代码如下:
```
private void initData() {
BNRoutePlanInfos routePlanInfos = null;
while (routePlanInfos == null) {
routePlanInfos = BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();
if (routePlanInfos == null) {
try {
Thread.sleep(100); // 延时100毫秒后重试
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 执行其他操作
}
```
这样就可以避免在使用routePlanInfos对象时出现NullPointerException异常了。