如何在android中使用接口作为响应侦听器



我有这段代码,我对控制流感到困惑。

这里的接口是如何用作响应侦听器的?LoginActivity类中重写的方法responseObject(JSONObject resp,String类型)是如何触发的?

在调用AsyncTask之后,控件会去哪里?

 public class LoginActivity extends Activity implements ResponseListener{
       login = (Button) findViewById(R.id.btnLogin);
       login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
            {
                 String username = mUsernameField.getText().toString();
                 String password = mPasswordField.getText().toString();
                 String[] param = {username, password};
                 new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);
            }
    @Override
    public void responseObject(JSONObject resp, String type) {
        try{
            if (resp.has("api_key")) {
                String api_key = resp.getString("api_key");
                String user_id = resp.getString("user");
                Log.i("api_key", api_key);
                SharedPreferences settings =     LoginActivity.this.getSharedPreferences(Constants.NADA_SP_KEY, 0);
                final SharedPreferences.Editor editor = settings.edit();
                editor.putString(Constants.NADA_API_KEY, api_key);
                editor.putString(Constants.NADA_USER_ID, user_id);
                editor.putBoolean(Constants.NADA_IS_LOGGED_IN, true);
                editor.commit();
                Log.i("first Visit", "False");
                String should_show_questions_screen = resp.getString("should_set_basic_questions");
                if (should_show_questions_screen.compareToIgnoreCase("true")==0){
                    Intent intent=new Intent(LoginActivity.this,RegistrationSuccessfulScreen.class);
                    startActivity(intent);
                    finish();

                }else {
                    Intent intent = new Intent(LoginActivity.this, UserNavigationActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }catch (JSONException e){
            e.printStackTrace();
        }
    }


//Heres my ServerRequest Class which uses AsyncTask
    public class ServerRequests {
      public static class LoginUserAsyncTask extends AsyncTask<String, Void, String> {
        static JSONObject udetails;
        Context mContext;
        ResponseListener mResponseListener;
        SweetAlertDialog progressDialog;
        public LoginUserAsyncTask(Context mContext,ResponseListener listener) {
            this.mContext = mContext;
            this.mResponseListener = listener;
        }
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog =new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
            progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
            progressDialog.setTitleText("please wait connecting..");
            progressDialog.setCancelable(false);
            progressDialog.show();

        }
        @Override
        protected String doInBackground(String... params) {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = null;
            udetails = new JSONObject();
            String response_data = "";
            if (params.length == 2) {
                try {
                    post = new HttpPost(Config.SERVER_BASE_URL + "/login");
                    udetails.put("username", params[0]);
                    udetails.put("password", params[1]);
                    SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
                    final SharedPreferences.Editor editor = settings.edit();
                    editor.putString(Config.USER_NAME, params[0]).commit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    post = new HttpPost(Config.SERVER_BASE_URL + "/login_with_fb");
                    udetails.put("fb_id", params[0]);
                    udetails.put("fb_auth_token", params[1]);
                    SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
                    final SharedPreferences.Editor editor = settings.edit();
                    editor.putString(Config.USER_NAME, params[0]).commit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            try {
                StringEntity se = new StringEntity(udetails.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                HttpResponse response = client.execute(post);
                int response_code = response.getStatusLine().getStatusCode();
                response_data = EntityUtils.toString(response.getEntity());
                Log.i("api_token", response_data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response_data;
        }
        @Override
        protected void onPostExecute(String response) {
            progressDialog.dismiss();
            JSONObject resp = new JSONObject();
            try {
                resp = new JSONObject(response);
                if (resp.has("status")) {
                    if (resp.getString("status").compareToIgnoreCase("unauthorised")==0){
                        AppMsg appMsg = AppMsg.makeText((Activity)mContext, resp.getString("message"), style);
                        appMsg.show();
                    }
                }
                mResponseListener.responseObject(resp,"LOGIN");
            } catch (JSONException e) {
                AppMsg appMsg = AppMsg.makeText((Activity)mContext, "Something went wrong", style);
                appMsg.show();
                e.printStackTrace();
            }
        }
}

//Here's Interface Which has this method

    public interface ResponseListener {
        public void responseObject(JSONObject data,String type);
    }

您的LoginActivity实现了ResponseListener。在这一行:new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);中,您将活动两次传递到LoginUserAsyncTask构造函数中。请注意,构造函数接受一个Context和一个ResponseListener。您可以这样做,因为您的活动实现了ResponseListener

现在LoginUserAsyncTask可以在您的活动中调用responseObject方法,因为它引用了ResponseListener。它在AsyncTaskonPostExecute方法中做到了这一点。该活动在某种程度上是列出任务完成时,然后调用它的responseObject方法。

由于AsyncTask的工作是异步完成的,所以它会"立即"返回并执行下一条语句。

我还认为你缺少的第一部分方法。

相关内容

最新更新