简体   繁体   English

如何等待Android UI线程中异步填充的对象而不阻止它?

[英]How can I wait for an object filled asynchronously in Android UI thread without blocking it?

I have a singleton to handle the registration and elimination of an entity Profilo ( a Profile). 我有一个人来处理实体Profilo(配置文件)的注册和删除。

This entity is set by passing an identifier and gathering information on the server in an async way. 通过传递标识符并以异步方式在服务器上收集信息来设置此实体。

My problem is that when I have to return my instance of profilo if it's not still loaded it will return null. 我的问题是,当必须返回仍未加载的profilo实例时,它将返回null。

public class AccountHandler {
    private static AccountHandler istanza = null;

    Context context;
    private boolean logged;
    private Profilo profilo;


    private AccountHandler(Context context) {
        this.context = context;
        //initialization
        //setting logged properly
            assignField(this.getName());
        }
    }

    public static AccountHandler getAccountHandler(Context context) {
        if (istanza == null) {
            synchronized (AccountHandler.class) {
                if (istanza == null) {
                    istanza = new AccountHandler(context);
                }
            }
        }
        return istanza;
    }

    public void setAccount(String nickname, String accessingCode) {
        logged = true;
        assignField(nickname);
    }

    //other methods

    private void assignField(String nickname) {
        ProfiloClient profiloClient = new ProfiloClient();
        profiloClient.addParam(Profilo.FIELDS[0], nickname);
        profiloClient.get(new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode,
                                  Header[] headers,
                                  JSONArray response) {
                JSONObject objson = null;
                try {
                    objson = (JSONObject) response.getJSONObject(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                AccountHandler accountHandler = AccountHandler.getAccountHandler(context);
    // Profilo is created with a JSONObject
    // **setProfilo is called in async**
                **accountHandler.setProfilo(new Profilo(objson));**
            }

        });
    }


    private void setProfilo(Profilo profilo) {
        this.profilo = profilo;
    }



    public Profilo getProfilo() {
        if( logged && profilo == null)
            //How can I wait that profilo is loaded by the JsonHttpResponseHandler before to return it

        return this.profilo;
    }


}

Instead of calling getProfilo you could use a callback mechanism in which the AccountHandler class notifies the caller when the profile has been loaded. 除了调用getProfilo您可以使用一种回调机制,在该机制中, AccountHandler类在加载配置文件时通知调用方。 eg 例如

  public void setAccount(String nickname, String accessingCode, MyCallback cb) {
      assignField(nickname, cb);
  }
  private void assignField(String nickname, MyCallback cb) {
      ....
      accountHandler.setProfilo(new Profilo(objson));
      cb.onSuccess(this.profilo);
  }

Create an inner Interface MyCallback (rename it) in your AccountHandler class AccountHandler类中创建一个内部接口MyCallback (重命名)

public class AccountHandler {
    public interface MyCallback {
        void onSuccess(Profilo profile);
    }
}

Now whenever you call setAccount you will pass the callback and get notified when the profile is available eg 现在,无论何时调用setAccount您都将传递回调并在配置文件可用时得到通知,例如

accountHandler.setAccount("Test", "Test", new AccountHandler.MyCallback() {
        void onSuccess(Profilio profile) {
            // do something with the profile
        }
    }

I added, as @Murat K. suggested, an interface to my Class that will provide a method to be call with the object when it is ready to be used. 正如@Murat K.所建议的那样,我添加了我的类的接口,该接口将提供一种可以随时使用的对象调用方法。

   public class AccountHandler {

    public interface Callback {
            void profiloReady(Profilo profilo);
    }
}

This method is called in getProfilo in a Handler that makes recursive calls to getProfilo until profilo is ready to be used, then it call the callback method which class is passed as argument of getProfilo. 在处理程序中的getProfilo中调用此方法,该处理程序对getProfilo进行递归调用,直到准备使用profilo为止,然后调用该回调方法,该类作为getProfilo的参数传递。

public void getProfilo(final Callback Callback) {
    if( logged && (profilo == null || !profilo.isReady() ) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getProfilo(Callback);
            }
        }, 500);
    }else
        Callback.profiloReady(profilo);
}

Example of getProfilo call getProfilo调用示例

public class ProfiloCall implements AccountHandler.MyCallback {

        @Override
        public void profiloReady(Profilo profilo) {
            //Use profilo as needed
            //EXECUTED ONLY WHEN PROFILO IS READY
        }


        public void callerMethod() {
            //useful code
            accountHandler.getProfilo(this);
            //other useful code

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何等待下载线程完成然后返回而又不阻塞UI线程? - How to wait for downloading thread to finish and then return without blocking UI thread? Android Asynctask:等待整个计算而不会阻塞UI线程 - Android Asynctask: wait for entire computation without blocking UI thread 等待接收数据而不阻止ui线程蓝牙android - Wait to receive data without blocking ui thread bluetooth android 如何在不阻止UI线程的情况下转移Android资产? - How do I transfer an Android asset without blocking the UI thread? 如何在不锁定 UI 线程的情况下在 Android 中等待? - How to wait in Android without locking the UI thread? 如何在 android 中等待多个线程完成而不阻塞 ui? - How to wait for multiple threads to finish without blocking ui in android? 如何在不阻止UI的情况下使等待AsyncTask android的主线程 - How to make a Main Thread waiting for the AsyncTask android, without blocking the UI Android在UI线程中等待而不冻结它 - Android wait in UI thread without freezing it Android中的线程阻止UI - Thread blocking UI in android 如何在不阻止UI的情况下在屏幕上显示值,并使其在Android活动中以样式淡出? - How can I show a value on the screen without blocking the UI and make it fade out with style in android activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM