Implement Thread Android in my class?

后端 未结 2 1678
自闭症患者
自闭症患者 2021-01-25 07:35

I would like to know how to implement a thread in this class to make it safe from the problems of ANR (Application Not Responding)

public class myClass {


    p         


        
2条回答
  •  鱼传尺愫
    2021-01-25 08:07

    You don't want to use a Thread, but an AsyncTask. Here's how:

    Based on the following, figure out what you need for your app: AsyncTask

    Some inspiration:

    public class MyClass {
          //Something
    
          public MyClass() {
                new BackgroundTask().execute("Hello World");
          }
    }
    
    private class BackgroundTask extends AsyncTask {
    
          @Override
          protected void onPreExecute() {
                // Prepare your background task. This will be executed before doInBackground
          }
    
          @Override
          protected String doInBackground(String... params) {
                // Your main code goes here
    
                String iAmAString = "I have done something very heavy now...";
                return iAmAString;
          }      
    
          @Override
          protected void onPostExecute(String result) {
                // Whatever should happen after the background task has completed goes here
          }
    
    
    
          @Override
          protected void onProgressUpdate(Void... values) {
                // In here, you can send updates to you UI thread, for example if you're downloading a very large file.
          }
    }   
    

提交回复
热议问题