android:如何在继续之前等待监听器完成?

时间:2014-11-25 17:52:30

标签: android multithreading

我使用socialAuth插件将用户连接到我的应用中的linkdin。我正确设置了连接并检索数据。但是,我不确定如何让我的主要活动等到socialAuthListener已经触发并完成。我对线程知之甚少,但我以前还没有和听众一起使用过。这是我的代码:

public  class LinkdinAuth {

private static final String TAG = "TEST";
// SocialAuth Components
SocialAuthAdapter adapter;
ProgressDialog mDialog;

private Context context;
private boolean loggedIn = false;
private Bundle LinkdinData;


public LinkdinAuth(Context C){

    this.context = C;
    LinkdinData = new Bundle();
    adapter = new SocialAuthAdapter(new ResponseListener());

}       

public void adapterAuthorize(View v){
    adapter.authorize(v.getContext(), Provider.LINKEDIN);
}



private final class ResponseListener implements DialogListener
{
   public void onComplete(Bundle values) {
           String providerName = values.getString(SocialAuthAdapter.PROVIDER);
           Log.d("Main", "providername = " + providerName);

           mDialog = new ProgressDialog(context);
           mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
           mDialog.setMessage("Loading...");

           //Get profile information
           adapter.getUserProfileAsync(new ProfileDataListener()); 

           // get Job and Education information
           mDialog.show();
           adapter.getCareerAsync(new CareerListener());

           loggedIn = true;
            Log.d("Main", "LOGGED IN = " + loggedIn );
           Toast.makeText(context, providerName + " connected", Toast.LENGTH_SHORT).show();

       }

    @Override
    public void onBack() {
        Log.d("Main", "Dialog Closed by pressing Back Key");        
    }

    @Override
    public void onCancel() {
        Log.d("Main", "Cancelled");     
    }

    @Override
    public void onError(SocialAuthError e) {
        Log.d("Main", "Error");
        e.printStackTrace();

    }
}




// To receive the profile response after authentication
private final class ProfileDataListener implements SocialAuthListener<Profile> {

@Override
public void onExecute(String provider, Profile t) {

   Log.d("Sign Up", "Receiving Data");
    mDialog.dismiss();

   Profile profileMap = t;

   LinkdinData.putString("Validated ID",  profileMap.getValidatedId() );
   LinkdinData.putString("First Name", profileMap.getFirstName());
   LinkdinData.putString("Last Name", profileMap.getLastName());
   LinkdinData.putString("Email", profileMap.getEmail());
   LinkdinData.putString("Country", profileMap.getCountry());
   LinkdinData.putString("Language", profileMap.getLanguage());
   LinkdinData.putString("Location", profileMap.getLocation());
   LinkdinData.putString("Profile Image URL", profileMap.getProfileImageURL());
}

    @Override
    public void onError(SocialAuthError arg0) {
        // TODO Auto-generated method stub

    }
}


private final class CareerListener implements SocialAuthListener<Career> {

    @Override
    public void onExecute(String provider, Career t) {

        Log.d("Custom-UI", "Receiving Data");
        mDialog.dismiss();
        Career careerMap = t;

        //get education
        Log.d("Main", "Education:");
        if(careerMap.getEducations() != null){
            for(Education E: careerMap.getEducations()){
                Log.d("Main",  "School         = " +E.getSchoolName() );
                Log.d("Main",  "Major         = " + E.getFieldOfStudy() );
                Log.d("Main",  "Degree         = " + E.getDegree() );
                Log.d("Main",  "Start Date         = " + E.getStartDate() );
                Log.d("Main",  "End Date         = " + E.getEndDate() );
            }
        }




        Log.d("SignUp", "Career");
        if(careerMap.getPositions() != null){
            for(Position P: careerMap.getPositions()){
                 LinkdinData.putString("Company Name", P.getCompanyName() );
                 LinkdinData.putString("Job Title", P.getTitle() );
                Log.d("Main",  "Industry         = " + P.getIndustry() );
                Log.d("Main",  "Start Date         = " + P.getStartDate() );
                Log.d("Main",  "End Date         = " + P.getEndDate() );

            }
        }
    }

    @Override
    public void onError(SocialAuthError e) {
    }
}

public boolean isLoggedIn(){
    return loggedIn;
}

public Bundle getLinkdinData(){
    return LinkdinData;
}

所以,正如你所看到的那样。我有2个听众在授权通过后获取数据。我的主要活动是创建一个实例,调用adapterAuthroizeMethod,然后设置用户登录标志。然后调用getLinkedData。但是我希望它等到我知道监听器在调用getlinkdinData之前已经解雇了。这是按下按钮后我的主要活动的作用:

                L.adapterAuthorize(v);
                loggedInWithLinkdin = L.isLoggedIn();
                Bundle B = L.getLinkdinData();
                Intent i = new Intent(getBaseContext(), UserRegistration.class);
                i.putExtra("linkdin bundle", B);
                //startActivity(i);

有什么想法吗?

感谢

1 个答案:

答案 0 :(得分:0)

不是推荐的解决方案,而是更多的技巧。 这是您可以做的。

将aync调用环绕此构造:

AtomicBoolean done = new AtomicBoolean(false);
Global ans; // the return value holder
    try{
        result = someAsyncCall(query, new Thread()); // this new thread is for listener callback
        result.setResultListener(result -> {
            // do something with result.
            ans = result.getAns() ; // set global ans 
            done.set(true);
            synchronized (done) {
                done.notifyAll(); // notify the main thread which is waiting
            }
        });
    }
    catch (Exception e ) {
        Log(e);
    }
    synchronized (done) {
        while (done.get() == false) {
            done.wait(); // wait here until the listener fires
        }
    }
    return ans; // return global ans