我的asynctask有问题加载url的内容,内容有时间加载到字符串,我被迫做Thread.Sleep等待内容加载,我确定是不是ri ght方式,所以我问你什么是没有那个内容的正确方法
我的AsynTask:
package fungames.fungames;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
class GetContent extends AsyncTask<String, Void, String> {
protected String result = "";
protected int done = 0;
@Override
protected String doInBackground(String[] params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "FGAPP");
HttpResponse resulte = httpClient.execute(httpPost);
HttpEntity entity = resulte.getEntity();
result = EntityUtils.toString(entity,"UTF-8");
}
catch(Exception i) {
result = i.toString();
}
done = 1;
return result;
}
protected void onPostExecute(String message) {
}
}
我的Loader:
public static void Example() {
String values = Servers.Load();
}
public static String Load() {
String url = "http://example.com";
GetContent job = new GetContent();
job.execute(url);
return Do2(job);
}
public static String Do2(GetContent job)
{
String game = job.result;
if (game != "") {
return game;
}
} else {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
return Do2(job);
}
}
谢谢你!
答案 0 :(得分:0)
在AsyncTask类中创建一个接口:
class GetContent extends AsyncTask<String, Void, String> {
protected String result = "";
protected int done = 0;
protected String action = "";
public interface SendResult {
void onTaskFinished(String result,String action);
}
public SendResult resultInterface = null;
public GetContent(SendResult interface,String action){
resultInterface = interface;
this.action = action;
}
@Override
protected String doInBackground(String[] params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "FGAPP");
HttpResponse resulte = httpClient.execute(httpPost);
HttpEntity entity = resulte.getEntity();
result = EntityUtils.toString(entity,"UTF-8");
}
catch(Exception i) {
result = i.toString();
}
done = 1;
return result;
}
protected void onPostExecute(String message) {
resultInterface.onTaskFinished(message,action);
}
}
在您的活动中实施该界面:
public class MainActivity extends AppCompatActivity
implements GetContent.SendResult{
@Override
public void onCreate(Bundle savedInstanceState) {
String url = "http://example.com";
fetchDataForUrl(url,"RequestType-1");
}
public void fetchDataForUrl(String url,String action){
GetContent job = new GetContent(this,action);
job.execute(url);
}
@Override
void onTaskFinished(String result,String action){
//Here you will receive the result.
//Do what ever you want here.
if(action.equals("RequestType-1")){
//access result here.
}
}
}