This method can not be called from the main application thread
时间: 2024-05-18 20:18:40 浏览: 9
当我们在主线程中访问一些耗时的操作,比如网络请求、文件读写等,会导致主线程被阻塞,从而造成界面卡顿,用户体验不好。为了避免这种情况,我们通常会将耗时操作放到子线程中进行,然后再将结果返回到主线程更新UI。如果在主线程中调用了一些不允许在主线程中执行的方法,就会抛出“This method can not be called from the main application thread”异常。
下面是一个常见的例子,当在主线程中进行网络请求时,就会抛出该异常:
```java
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//创建一个TextView控件
textView = new TextView(this);
textView.setText("Hello, UI Thread!");
//将TextView控件添加到当前Activity的界面中
setContentView(textView);
//在主线程中进行网络请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
Response response = client.newCall(request).execute(); //抛出异常
String result = response.body().string();
//更新UI
textView.setText(result);
}
}
```
在这个例子中,我们在主线程中进行了一个网络请求,并且在请求完成后试图更新UI。由于网络请求是一个耗时操作,如果直接在主线程中执行,就会导致主线程被阻塞,从而造成界面卡顿。因此,OkHttpClient会抛出“This method can not be called from the main application thread”异常。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)