我的AsyncTask在android中没有在后台执行,为什么



My AsyncTask没有执行doInBackground,preExecute正在运行,我用Toast测试了它。

我也在运行另一个异步任务,但当我启动这个任务时,我取消了那个任务,它仍然不起作用。

它没有抛出任何错误,这仍然发生在我身上。

这是我的代码,任何帮助都将不胜感激。

一些代码被截断了。我只是在展示重要的部分。

如果我的英语有任何错误,我很抱歉。

// AsyncTask
package com.test.testing;
//imports 
public class Update_Score extends AsyncTask<Void, Void, Void> {
String result="vvv",
name,
score,
lastTest,
maximum;
ProgressBar loading;
TextView text;
Context context;
@Override
protected Void doInBackground(Void... voids) {
String strUrl="http://test.tk/updatesomething.php";
while (result=="vvv") {
try {
URL url = new URL(strUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
//output
OutputStream output = httpConnection.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
String post_data= URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("score","UTF-8")+"="+URLEncoder.encode(score,"UTF-8")+"&"
+URLEncoder.encode("lastTest","UTF-8")+"="+URLEncoder.encode(lastTest,"UTF-8");
writer.write(post_data);
writer.flush();
writer.close();
output.close();
//input
InputStream input = httpConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(input,"iso-8859-1"));
result="";
String line="";
while ((line=reader.readLine())!=null){
result += line;
}
reader.close();
input.close();
httpConnection.disconnect();
} catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) {
e.printStackTrace();
}
}
new AlertDialog.Builder(context).setMessage("updateEnd").create().show();
return null;
}
}


// Calling AsyncTask
package com.test.testing;
//imports
public class Final_Score extends AppCompatActivity {
public TextView score;
public ProgressBar loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final__score);
initVar();
String totalMark =getIntent().getStringExtra("TOTAL_MARKS"),
name =getIntent().getStringExtra("NAME") ,
lastTest =getIntent().getStringExtra("TESTNUM"),
maximum =getIntent().getStringExtra("MAX");
boolean forced=getIntent().getBooleanExtra("FORCED",false);
if(forced){
new AlertDialog.Builder(this).setMessage("Time Up").setTitle("").create().show();
}
score.setText(totalMark);
Update_Score update=new Update_Score(name,totalMark,lastTest,loading,this,score,maximum);
update.execute();
}
}

提前谢谢。

我遇到了问题,我说正在运行的任务也没有取消,即使我调用AsyncTask.cancel(true)这是一个循环的任务,直到达到特定的时间(如11:17(。

while(!mainActivity.timeNotEnds){
//some stuff here
if (time==previouslySpecifiedTime){
break;
}       

}

因此,我在主活动中创建了一个布尔值,并将该任务中的代码设置为while(!mainActivity.timeNotEnds)

相关内容

  • 没有找到相关文章

最新更新