如何让java等待boolean运行函数

时间:2013-11-11 09:35:07

标签: java android timer response

我确信这很简单,但我无法弄明白,这很糟糕,我很容易接受(应该是什么)一个简单的步骤。

确定。我有一个方法运行一个给出响应的函数。这个方法实际上处理文件的上传,所以需要一秒钟才能给出响应。我需要在以下方法中进行此响应。 sendPicMsg需要完成,然后转发它对sendMessage的响应。请帮忙。

b1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        if(!uploadMsgPic.equalsIgnoreCase("")){

            Log.v("response","Pic in storage");
            sendPicMsg();
                    sendMessage();
            }else{
                    sendMessage();
                }

第一种方法

public void sendPicMsg(){ 
Log.v("response", "sendPicMsg Loaded");
if(!uploadMsgPic.equalsIgnoreCase("")){

  final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
    AsyncHttpClient client3 = new AsyncHttpClient();
    RequestParams params3 = new RequestParams();

    File file = new File(uploadMsgPic);

    try {
        File f = new File(uploadMsgPic.replace(".", "1."));
        f.createNewFile();

        //Convert bitmap to byte array
        Bitmap bitmap = decodeFile(file,400);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();

        //write the bytes in file
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(bitmapdata);


        params3.put("file", f);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    params3.put("email", preferences.getString("loggedin_user", ""));
    params3.put("webversion", "1");
    client3.post("http://*******.com/apiweb/******upload.php",params3, new AsyncHttpResponseHandler() {

      @Override
      public void onSuccess(String response) {
          Log.v("response", "Upload Complete");

          refreshChat();
        //responseString = response;
        Log.v("response","msgPic has been uploaded"+response);
        //parseChatMessages(response);
        response=picurl;
        uploadMsgPic = "";

        if(picurl!=null){
            Log.v("response","picurl is set");
        }
        if(picurl==null){
                Log.v("response", "picurl no ready");
                };

      }




  });

    sendMessage();

}                         


  }

第二种方法

public void sendMessage(){ 

  final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
  if(preferences.getString("Username", "").length()<=0){
      editText1.setText("");
      Toast.makeText(this.getActivity(), "Please Login to send messages.", 2);
      return;
  }
    AsyncHttpClient  client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    if(type.equalsIgnoreCase("3")){
        params.put("toid",user);
         params.put("action", "sendprivate");
    }else{
        params.put("room", preferences.getString("selected_room", "Adult Lobby"));
         params.put("action", "insert");

    }
    Log.v("response", "Sending message "+editText1.getText().toString());
params.put("message",editText1.getText().toString() );
params.put("media", picurl);

 params.put("email", preferences.getString("loggedin_user", ""));
params.put("webversion", "1");


  client.post("http://peekatu.com/apiweb/*********.php",params, new AsyncHttpResponseHandler() {

      @Override
      public void onSuccess(String response) {

          refreshChat();
        //responseString = response;
        Log.v("response", response);
        //parseChatMessages(response);
        if(picurl!=null)
        Log.v("response", picurl);
      }



  });





  editText1.setText("");
    lv.setSelection(adapter.getCount() - 1);

  }

3 个答案:

答案 0 :(得分:0)

不要将此IO和RPC密集型与客户端线程混合使用。单击按钮时,启动另一个处理通信的线程。

在该线程(可能是一个单独的类)中,您发送图片并等待响应;同时将您的按钮标记为禁用以避免再次单击。然后,当您收到回复时,再次发送该消息。然后,将事件提升回GUI线程,启用按钮并显示消息。

答案 1 :(得分:0)

解决这个问题的简单方法;在“onSuccess()”方法中的sendPicMsg()之后调用你的方法sendMessage()

答案 2 :(得分:0)

据我了解,您需要连续执行后台任务。 我在这种情况下所做的是使用一个扩展AsyncTask的类,在其构造函数中使用某种侦听器并在onPostExecute中调用侦听器的回调。

一个简单的例子:

class ExampleTask<T,S,U> extends AsyncTask<T,S,U>
{
    public interface ExampleListener
    {
        public void onTaskCompleted(boolean success);
    }

    private ExampleListener mListener;

    public ExampleTask(ExampleListener listener)
    {
        mListener = listener;
    }

    ...
    @Override
    protected void onPostExecute(U result)
    {
        ...
        if (mListener != null)
        {
            mListener.onTaskCompleted(yourBooleanResult);
        }
    }
}

只需传递一个调用第二个方法的新ExampleListener实现。 这是一个监听器的实现:

ExampleListener sendMessageListener = new ExampleListener()
{
    public void onTaskCompleted(boolean success)
    {
        if(success)
            sendMessage();
    }
}