how to add runOnUiThread() in my Activity

后端 未结 2 496
执笔经年
执笔经年 2021-01-28 11:07

I added the AsyncTask to offload network operations to a background thread.I need to make sure the UI operations are on the UI thread.So i want to Use runOnUiThread() in my Acti

2条回答
  •  迷失自我
    2021-01-28 11:23

    I added the AsyncTask to offload network operations to a background thread.I need to make sure the UI operations are on the UI thread.So i want to Use runOnUiThread() in my Activity.

    Ugh! No!!! Every method of AsyncTask runs on the UI Thread except for doInBackground(). So do your network operations in doInBackground() and update the UI in onPostExecute() or in onProgressUpdate() by calling publishProgress() from doInBackground().

    Do not use runOnUiThread() with AsyncTask. There is no reason, at least known to me, to use that with AsyncTask since it has methods that already run on the UI Thread. I have never seen it do anything but cause trouble.

    You can either call publishProgress() from your loop and update your TextView in onProgressUpdate() or add the values to an ArrayList and update in onProgressUpdate().

    Please read the docs several times. AsyncTask is a bit tricky at first but once you learn what it does then it can be a beautiful thing.

    Edit

    Create an instance of your AsyncTask and pass your Activity Context to it

    Scan myScan = new scan(this); // pass the context to the constructor
    myScan.execute();
    

    Then create a constructor in your AsyncTask and have it accept a Context.

    public class scan extends AsyncTask 
    {
    
         public Object WIFI_SERVICE;
         public Context context;   // Context variable
    
         public scan(Context c)  // constructor to take Context
         {
             context = c;   // intialize your Context variable
         }
    

    Now use that variable

        @Override
        protected String doInBackground(String... params) 
        {
            wifiApManager = new WifiApManager(context);  // use the variable here
            return null;
        }
    

    Another Edit

    class scan extends AsyncTask {
         ArrayList clients;
         Context context;
    
    ...
    
    then initialize your `clients` in `doInBackground()`
    
    clients = wifiApManager.getClientList(false);
    

    change onPostExecute() to not accept anything

    protected void onPostExecute(Void result){
    

    and put your code that updates the TextView in there.

提交回复
热议问题