Android - 执行 AsyncTask 线程的问题

Posted

技术标签:

【中文标题】Android - 执行 AsyncTask 线程的问题【英文标题】:Android - Problem with executing AsyncTask thread 【发布时间】:2021-05-19 05:12:57 【问题描述】:

我正在尝试编写一个在异步任务上发送POST 请求的应用程序。我的AsyncTask 似乎没有执行,因为我的进度条没有出现。我真的不知道这里出了什么问题,因为我遵循了许多解决方案/教程。 这是我的代码:

register.java

public class register extends AppCompatActivity 

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        final Activity thisActivity = this;
        final EditText userNameEditText = findViewById(R.id.registerUsername);
        final EditText emailEditText = findViewById(R.id.registerEmail);
        final EditText passwordEditText = findViewById(R.id.registerPassword);
        final ProgressBar progressBar = findViewById(R.id.progressBar);
        Button btnRegisterDB = findViewById(R.id.btnRegistrationDB);
        final TextView respondText = findViewById(R.id.responseRegister);
        btnRegisterDB.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                String username = String.valueOf(userNameEditText.getText());
                String email = String.valueOf(emailEditText.getText());
                String password = String.valueOf(passwordEditText.getText());
                //execute asynchronous task in background and wait for response
                RegisterParams params = new RegisterParams(username, email, password);
                registrationDB async = new registrationDB();
                async.setProgressBar(progressBar);
                async.setRespondText(respondText);
                async.getParentActivity(thisActivity);
                async.execute(params);
            
        );
    
    
    public boolean onOptionsItemSelected(MenuItem item)
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        return true;
    
    
    public static class RegisterParams 
        public String username;
        public String email;
        public String password;

        RegisterParams(String username, String email, String password)
            this.username = username;
            this.email = email;
            this.password = password;
        
    

这里是 registrationDB.java

public class registrationDB extends AsyncTask<register.RegisterParams, Void, String> 

    openHTTP openHTTP = new openHTTP();
    String respond;

    ProgressBar pb;
    TextView respondTextView;
    Activity parentActivity;

    public void setProgressBar(ProgressBar progressBar)
        this.pb = progressBar;
    

    public void setRespondText(TextView textView)
        this.respondTextView = textView;
    

    public void getParentActivity(Activity parentActivity)
        this.parentActivity = parentActivity;
    

    @Override
    public void onPreExecute()
        pb.setVisibility(View.VISIBLE);
        //parentActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
        //        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        super.onPreExecute();
    
    
    @Override
    protected String doInBackground(register.RegisterParams... params) 
        try 
            HttpURLConnection httpConn = openHTTP.prepareConnection("someurl");
            String jsonInputString = " username: " + params[0].username +", email: " + params[0].email
                    + ", password: " + params[0].password + "";
            try(OutputStream os = httpConn.getOutputStream()) 
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
             catch (Exception e)
                e.printStackTrace();
            
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(httpConn.getInputStream(), "utf-8"))) 
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) 
                    response.append(responseLine.trim());
                
                respond = response.toString();
                return respond;
             catch (Exception e)
                e.printStackTrace();
            

         catch (Exception e) 
            e.printStackTrace();
        
        return null;
    

    @Override
    protected void onPostExecute(String s) 
        pb.setVisibility(View.GONE);
        respondTextView.setText(s);
        super.onPostExecute(s);
    

我有外部类 openHTTP.java 负责打开 HttpUrlConnection:

public class openHTTP 

    public openHTTP()

    
    //provide URL to external file that you want make POST request to
    public HttpURLConnection prepareConnection(String URL)
        try 
            java.net.URL url = new URL(URL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);
            return con;
         catch (Exception e) 
            e.printStackTrace();
        
        return null;
    

提前感谢您的帮助!

更新

在记录进程后,我发现了该异常: java.io.IOException: Cleartext HTTP traffic to url not permitted,我正在寻找这个问题的路上

我的解决方案

所以,在 androidManifest.xml 中添加 android:usesCleartextTraffic="true" 就足够了 感谢您的帮助!

【问题讨论】:

android studio 是您编写代码的 IDE,但它根本不会改变代码的结果,所以如果您不询问 IDE 的功能,这里有无需使用标签 我明白了,我会改的 我已经删除了,我只是在解释原因 使用Log.i()检查哪些方法被调用,哪些没有...检查Android Studio中的Logcat选项卡,也许有异常堆栈跟踪? 我会努力做到的 【参考方案1】:

在记录进程后,我发现了该异常:java.io.IOException: Cleartext HTTP traffic to url not permitted

所以,在 AndroidManifest.xml 中添加 android:usesCleartextTraffic="true" 就足够了,感谢您的帮助!

【讨论】:

以上是关于Android - 执行 AsyncTask 线程的问题的主要内容,如果未能解决你的问题,请参考以下文章

Android AsyncTask内部线程池异步执行任务机制简要分析

Android 对线程封装了:AsyncTask, HandlerThread和线程池。 有知道这三个如何选择吗?

Android在不同的线程池中执行AsyncTask

AsyncTask-Android

android asynctask怎么用

Android AsyncTask分析