gpt4 book ai didi

java - Android AsyncTask 从 URL 读取数据返回 android.os.NetworkOnMainThreadException

转载 作者:行者123 更新时间:2023-12-01 08:03:52 24 4
gpt4 key购买 nike

我是 Android 新手,正在为我制作的简单扫雷游戏制作全局高分功能。我使用 PHP 制作了高分功能,因此它只需访问带有一些获取参数的 URL,分数就会自动保存。要获得类似的分数,应该将 URL 的 JSON 内容读取到字符串中。

我知道你无法从主线程访问网络,所以我创建了一个 AsyncTask。然后我从我的 Activity 中调用它。

但我仍然收到错误 android.os.NetworkOnMainThreadException

下面是AsyncTask类

package net.as93.minesweeper.util;

import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Eventupdate extends AsyncTask<String, Void, Void> {

String pageContents;

@Override
protected Void doInBackground(String... url) {
try {

Thread.sleep(4000);

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url[0]);
HttpResponse response = httpClient.execute(httpGet,localContext);
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

String line = null;
while ((line = reader.readLine()) != null) {
result += line + "\n";
}
pageContents = result;

} catch (InterruptedException e) {
System.out.println(e);
e.printStackTrace();


} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// TODO Auto-generated method stub
return null;
}

public String getPageContents() {
return pageContents;
}

}

这是应该调用 AsyncTask 的 saveScore() 方法

public void saveScore(ScoreObj scoreObj) throws IOException {
String usersname = scoreObj.getUsersName();
String time = Integer.toString(scoreObj.getTime());
String mode = scoreObj.getGameMode();
String timed = ((scoreObj.isTimed()) ? "true" : "false");

String myUri = "http://android.as93.net/minesweeper/setscore.php?usersname="+usersname+"&time="+time+"&timed="+timed+"&mode="+mode;
try{
Eventupdate eu = new Eventupdate();
eu.execute(myUri);
eu.doInBackground(myUri);


}catch (Exception e){System.out.println("Another error: "+e);}


}

我已经添加了<uses-permission android:name="android.permission.INTERNET"/>到 list

我花了很多时间试图解决这个问题,但在互联网上找不到解决方案。预先感谢您的任何建议

最佳答案

这部分是可疑的

Eventupdate eu = new Eventupdate();
eu.execute(myUri);
eu.doInBackground(myUri);

当您调用execute时,不要直接调用doInBackground,它会自行调用

关于java - Android AsyncTask 从 URL 读取数据返回 android.os.NetworkOnMainThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23086805/

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