how to do functions in an AsyncTask?

前端 未结 3 931
名媛妹妹
名媛妹妹 2021-01-23 06:59

I have to use directions() function in an AsyncTask to avoid network processing on the UI thread.i\'m unable to do this thing. MY code is

    public class MainAc         


        
3条回答
  •  时光说笑
    2021-01-23 07:43

    This is the basic structure of an AsyncTask

    public class TalkToServer extends AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
    
        }
    
        @Override
        protected String doInBackground(String... params) {
        //do your work here
            return something;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
               // do something with data here-display it or send to mainactivity
    }
    

    you can do your network stuff and/or stuff that you have in directions in doInBackground() and update UI on the other methods. You can also put the directions method as a private method of your AsyncTask

    Then you would call this from your MainActivity like

    TalkToServer networkStuff = new TalkToServer(); //could pass params to a constructor here such as context
    networkStuff.execute();
    

    If the AsyncTask isn't an inner class of your MainActivity then you will need a constructor to receive the context from your MainActivity if you want to do UI stuff

提交回复
热议问题