我的Android中的AsyncTask未执行后台操作,为什么?

huangapple go评论76阅读模式
英文:

My AsyncTask in android not executing do in background , Why?

问题

// AsyncTask

package com.test.testing;

// 导入语句

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);

                // 输出

                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();

                // 输入

                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;
    }

}



// 调用 AsyncTask

package com.test.testing;

// 导入语句

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();

    }

}
英文:

My AsyncTask not executing doInBackground , preExecute is running i tested it with a Toast .

I am also running another asynctask but when i starts this one i cancels that one still it wont works.

It's not throwing any errors still this happens to me.

Here's my code any help will be appreciated .

some codes are been cutted off . I am just showing the important parts.

And sorry if there's any mistake in my english.

// AsyncTask

package com.test.testing;

//imports 
public class Update_Score extends AsyncTask&lt;Void, Void, Void&gt; {

    String result=&quot;vvv&quot;,
            name,
            score,
            lastTest,
            maximum;

    ProgressBar loading;

    TextView text;

    Context context;

    @Override
    protected Void doInBackground(Void... voids) {
        String strUrl=&quot;http://test.tk/updatesomething.php&quot;;
        while (result==&quot;vvv&quot;) {

            try {

                URL url = new URL(strUrl);

                HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

                httpConnection.setRequestMethod(&quot;POST&quot;);
                httpConnection.setDoOutput(true);
                httpConnection.setDoInput(true);

                //output

                OutputStream output = httpConnection.getOutputStream();
                BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,&quot;UTF-8&quot;));
                String post_data= URLEncoder.encode(&quot;name&quot;,&quot;UTF-8&quot;)+&quot;=&quot;+URLEncoder.encode(name,&quot;UTF-8&quot;)+&quot;&amp;&quot;
                        +URLEncoder.encode(&quot;score&quot;,&quot;UTF-8&quot;)+&quot;=&quot;+URLEncoder.encode(score,&quot;UTF-8&quot;)+&quot;&amp;&quot;
                        +URLEncoder.encode(&quot;lastTest&quot;,&quot;UTF-8&quot;)+&quot;=&quot;+URLEncoder.encode(lastTest,&quot;UTF-8&quot;);

                writer.write(post_data);
                writer.flush();
                writer.close();
                output.close();

                //input

                InputStream input = httpConnection.getInputStream();
                BufferedReader reader=new BufferedReader(new InputStreamReader(input,&quot;iso-8859-1&quot;));
                result=&quot;&quot;;
                String line=&quot;&quot;;

                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(&quot;updateEnd&quot;).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(&quot;TOTAL_MARKS&quot;),
                name =getIntent().getStringExtra(&quot;NAME&quot;) ,
                lastTest =getIntent().getStringExtra(&quot;TESTNUM&quot;),
                maximum =getIntent().getStringExtra(&quot;MAX&quot;);

        boolean forced=getIntent().getBooleanExtra(&quot;FORCED&quot;,false);

        if(forced){

            new AlertDialog.Builder(this).setMessage(&quot;Time Up&quot;).setTitle(&quot;&quot;).create().show();

        }

        score.setText(totalMark);
        Update_Score update=new Update_Score(name,totalMark,lastTest,loading,this,score,maximum);
        update.execute();

    }

}

Thanks in advance.

答案1

得分: 1

我遇到的问题是,我之前提到的任务仍在运行,即使我调用了AsyncTask.cancel(true)也无法取消。
这是一个循环任务,会一直循环直到达到特定的时间(比如11:17)。

while(!mainActivity.timeNotEnds){

   //一些操作在这里

   if (time==previouslySpecifiedTime){

       break;

   }       
}

所以我在主活动中创建了一个布尔变量,并将任务中的代码改为

while(!mainActivity.timeNotEnds)
英文:

I got the problem the task which i said was running also doesn't cancels even i calls AsyncTask.cancel(true)
it was a task whcih loops until a specific time (like 11:17) is reached .

while(!mainActivity.timeNotEnds){

   //some stuff here

   if (time==previouslySpecifiedTime){

       break;

   }       

}

so instead i made a boolean in the main activity and set the code in that task like
while(!mainActivity.timeNotEnds)

huangapple
  • 本文由 发表于 2020年10月3日 15:22:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64181729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定