如何从Android中的非UI线程更新UI?

时间:2016-04-08 08:28:30

标签: android

我有一个执行AsynkTask的登录片段,在onPost()中我想更新Login Fragment UI。我已经完成了需要在That中进行一些修正。如何制作非ui线程。

这是我的代码: -

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    m_Main = inflater.inflate(R.layout.login_screen, container, false);
    ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
    CMainActivity.m_Drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    m_oLoginSession = new CLoginSessionManagement(getActivity());
    init();// initialize controls
    return m_Main;
}

public void init() {
    m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);


    m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
    m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);

    m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
    m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
    m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
    m_ChangePass.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
        }
    });

    m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);

    m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
        }
    });
    m_LoginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new LoginAttempt().execute();
        }
    });
}

private class LoginAttempt extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setCancelable(false);
        pDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
        // and now the magic
        pDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        pDialog.getWindow().setGravity(Gravity.BOTTOM);
        pDialog.getWindow().getAttributes().verticalMargin = 0.5f;
        pDialog.show();

// CProgressBar.getInstance()。showProgressBar(getActivity(),&#34;请等待Logging ...&#34;); //显示进度..........         }

    @Override
    protected String doInBackground(String... params) {
        getLoginDetails();// getting login details from editText...........
        InputStream inputStream = null;
        m_oJsonsResponse = new CJsonsResponse();
        isFirstLogin = true;
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(s_szLoginUrl);
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("agentCode", s_szMobileNumber);
            jsonObject.put("pin", s_szPassword);
            jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            //  httpPost.setHeader("Accept", "application/json");   ///not required
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            // 9. receive response as inputStream
            inputStream = entity.getContent();
            System.out.print("InputStream...." + inputStream.toString());
            System.out.print("Response...." + httpResponse.toString());

            StatusLine statusLine = httpResponse.getStatusLine();
            System.out.print("statusLine......" + statusLine.toString());
            ////Log.d("resp_body", resp_body.toString());
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                // 10. convert inputstream to string
                if (inputStream != null) {
                    s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
                    //String resp_body =
                    EntityUtils.toString(httpResponse.getEntity());
                }
            } else
                s_szresult = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return s_szresult;
    }

    @Override
    protected void onPostExecute(final String response) {
        super.onPostExecute(response);
        m_Handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                m_Handler.post(new Runnable() {
                    @Override
                    public void run() {
                        CProgressBar.getInstance().hideProgressBar();// hide progressbar after getting response from server......
                        try {
                            m_oResponseobject = new JSONObject(response);// getting response from server
                            new Thread() {// making child thread...
                                public void run() {
                                    Looper.prepare();
                                    try {
                                        getResponse();// getting response from server ........
                                        Looper.loop();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    public void getResponse() throws JSONException {
        if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
            m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
            CToastMessage.getInstance().showToast(getActivity(), "You are successfully Logged In");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
            CToastMessage.getInstance().showToast(getActivity(), "Please Enter Valid Mobile Number");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
            CToastMessage.getInstance().showToast(getActivity(), "Please Enter Password");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
            CToastMessage.getInstance().showToast(getActivity(), "Please enter correct Password");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
            CToastMessage.getInstance().showToast(getActivity(), "You are blocked as You finished your all attempt");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
            CToastMessage.getInstance().showToast(getActivity(), "Connection Lost ! Please Try Again");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
            CToastMessage.getInstance().showToast(getActivity(), "User not found ! Kindly Regiter before Login");
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
            CToastMessage.getInstance().showToast(getActivity(), "Otp not Verify ! Kindly Generate Otp on Sign Up");
        }
    }

    public void getLoginDetails() {
        s_szMobileNumber = m_InputMobile.getText().toString();
        s_szPassword = m_InputPassword.getText().toString();
    }
}

}

3 个答案:

答案 0 :(得分:0)

onPostExecute()中某个帖子中的代码移动到doInBackground(),因为它在其他帖子中运行,并在onPostExecute()

中刷新UI

一个模拟的例子:

    @Override
    protected String doInBackground(String... params) {

        //RUN ALL THAT YOU WANT IN A DIFFERENT THREAD
    }

    @Override
    protected void onPostExecute(final String response) {
        //REFRESH THE UI
        }

答案 1 :(得分:0)

如果您正在使用AsynkTask,则可以尝试在UI线程上运行的onPreExecute和onPostExecute方法。

或者您可以使用处理程序更新UI。

答案 2 :(得分:0)

In your UI thread create an object of Handler like this

private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            //Update UI here
            //use msg.obj   if you have sent Object from background thread
            //use msg.what  if you have sent Integer from background thread

            //Update UI if you have just trigger the handler using sendEmptyMessage(your UI/View gets data from Global Variable)


        }
};

Two ways we can trigger Hanler which is created in UI thread
1)handler.sendMessage(Message);
2)handler.sendEmptyMessage(0);

   Inside on postExecute of your AsyncTask write below Code based on your requirement 
        //Message msg=Message.obtain();
        //msg.obj=YourObject;//If you want to pass Object
        //msg.what=Integer;//If you want to pass Integer

        //handler.sendMessage(msg);//to send Message objectdefined above
        handler.sendEmptyMessage(0);//If you simply want to trigger