2016-03-28 67 views
-5

我使用AsynkTask從服務器獲取數據,但它使用AsynkTask來減少主線程的負載。如何在AsynkTask中使用Handler。請幫我解決這個問題。如何在Android的AsynkTask中使用Handler

這是我的代碼。

public class CLoginScreen extends Fragment { 
public static String s_szLoginUrl = "http://192.168.0.999:8080/rest/json/metallica/getLoginInJSON"; 
public static String s_szresult = " "; 
public static String s_szMobileNumber, s_szPassword; 
public static String s_szResponseMobile, s_szResponsePassword; 
public View m_Main; 
public EditText m_InputMobile, m_InputPassword; 
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn; 
public CJsonsResponse m_oJsonsResponse; 
public boolean isFirstLogin; 
public JSONObject m_oResponseobject; 
public LinearLayout m_MainLayout; 
public CLoginSessionManagement m_oLoginSession; 

@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(); 
    m_oLoginSession = new CLoginSessionManagement(getActivity()); 
    init(); 
    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.setBackgroundColor(Color.TRANSPARENT); 
    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> { 
    public Dialog m_Dialog; 
    public ProgressBar m_ProgressBar; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     m_Dialog = new Dialog(getActivity()); 
     m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     m_Dialog.setContentView(R.layout.progress_bar); 
     showProgress("Please wait while Logging...");// showing progress .......... 
    } 

    @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()); 
     } 
     System.out.println("s_szResult....." + s_szresult); 
     System.out.println("password......" + s_szPassword); 
     // 11. return s_szResult 
     return s_szresult; 
    } 

    @Override 
    protected void onPostExecute(String response) { 
     super.onPostExecute(response); 
     hideProgress();// 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(); 
     } 
    } 

    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(); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) { 
      showToast("Please Enter Valid Mobile Number"); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) { 
      showToast("Please Enter Password"); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) { 
      showToast("Invalid Password"); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) { 
      showToast("You are blocked as You finished you all attempt"); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) { 
      showToast("Connection Lost ! Please Try Again"); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) { 
      showToast("User not found ! Kindly Regiter before Login"); 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) { 
      showToast("Otp not Verify ! Kindly Generate Otp on Sign Up"); 
     } 
    } 

    public void showToast(String message) {// method foe showing taost message 
     Toast toast = Toast.makeText(getActivity(), "" + message, Toast.LENGTH_SHORT); 
     toast.setGravity(Gravity.CENTER, 0, 0); 
     toast.show(); 
    } 

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

    public void showProgress(String message) { 
     m_ProgressBar = (ProgressBar) m_Dialog.findViewById(R.id.progress_bar); 
     TextView progressText = (TextView) m_Dialog.findViewById(R.id.progress_text); 
     progressText.setText("" + message); 
     progressText.setVisibility(View.VISIBLE); 
     m_ProgressBar.setVisibility(View.VISIBLE); 
     m_ProgressBar.setIndeterminate(true); 
     m_Dialog.setCancelable(false); 
     m_Dialog.setCanceledOnTouchOutside(false); 
     m_Dialog.show(); 
    } 

    public void hideProgress() { 
     m_Dialog.dismiss(); 
    } 
} 

}

+2

你不需要'AsyncTask'中的'Handler's,只需在UI線程中執行的回調內調用你的UI – pskink

+0

給我寫的代碼親愛的我是新的 – rahul

+0

asynctask用於在後臺線程上執行操作。 –

回答

0

您可以使用

 getActivity().runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      getResponse(); 
     } 
    }); 
+0

其中...我使用runonuiThread – rahul

+0

給出錯誤,而我添加runOnUiThread – rahul

0

按照Android的文檔here

異步任務是由一個 後臺線程,其運行的計算定義結果在UI線程上發佈。

並且使用Handler從URL加載數據不是一件好事。請使用ExecutorThreadPoolExecutor來完成繁重的後臺任務。

0

,你可以這樣做:

class MyAsyncTask extends AsyncTask<Object,Object,Object>{ 

    Private Context c; 
    private Handler handler; 

    private final static int YOUR_WORK_ID = 0x11; 

    public MyAsyncTask(Context c,Handler handler){ 
     this.c = c; 
     this.handler = handler; 

    } 

    protected Object doInBackground(Object... params){ 
     //do your work 
     ... 
     Message m = handler.obtainMessage(); 
     m.what = YOUR_WORK_ID; 
     ... 
     handler.sendMessage().sendToTarget(); 


    } 



} 

而在你的片段,你可以初始化一個處理程序PARAMS到MyAsyncTask,並處理你的handleMessage工作();

相關問題