using asynctask to speed up android app launch time

后端 未结 2 1351
抹茶落季
抹茶落季 2020-11-30 15:00

I have an app which load ads from two networks and sets a flash file to webview when started.This is making it too slow on startup, forums told me to use asynctask.Can some

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 15:20

    I can't just make your code an AsyncTask but I can give you an example and some help. This is an example of 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
    

    }

    All of your network stuff you will put in doInBackground() then if you need to update the UI you did that in the other methods. After finishing the network stuff you can update UI in onPostExecute().

    This is how you would call the task

    TalkToServer myAsync = new TalkToServer() //can add params if you have a constructor
    myAsync.execute() //can pass params here for `doInBackground()` method
    

    If it is an inner class of your MainActivity then it will have access to member variables of MainActivity. If its a separate class then you can pass context to constructor like

    TalkToServer myAsync = new TalkToServer(this);
    

    and create a constructor to accept Context and any other params you want

    I strongly suggest going through the docs below and make sure you understand how it works. Maybe the biggest thing to understand when getting started is that doInBackground() doesn't run on the UI so you don't want to try and update any Views here but in the other AsyncTask methods or by passing data back to the MainActivity and update there AsyncTask

提交回复
热议问题