在android中等待并通知

时间:2012-11-30 10:51:36

标签: java android multithreading thread-safety

我正在处理我的应用程序中的一个线程,我遇到了线程等待功能的问题。我使用runOnUIThread()创建并显示我的UI,我的主要版本正在等待我的UI线程完成,在完成后我在主线程中执行了一些过程,这里的问题是主进程始终处于等待状态我的线程完成它;我正在使用wait和notify()函数来完成这个

      public String LSVerification() {

        String t = null;

            t="Sample string";
            synchronized(this)

            {
            AndroidHTMLActivity.this.runOnUiThread(ShowDialog) ;//here i call my thread

            try {
               this.wait();//here i waiting for my thread to finish it's job

            //here i do some process after my thread finish it's job
              //the problem is here main process always in wait state


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

            }
          return t;        
        }

        private Runnable ShowDialog = new Runnable() {
            public void run() {
                String t = null;
        synchronized(ShowDialog)

            {
            Recognition recg=new Recognition(Activity.this);

                recg.show();


            this.notify();
            }

            }
        };

1 个答案:

答案 0 :(得分:1)

尝试使用处理程序在后台执行作业后更新UI ...

Link to Handlers请参阅以下代码..

private void performOperationInBackgroundThread() {
        Thread Servicethread = new Thread(
                    new Runnable() {
                        public void run() {
                            try {
                                PerformThreadOperation();
                                DataLoaded = true;
                            } catch (Exception e) {
                                ExceptionOccured = true;
                                e.printStackTrace();
                                System.out.println(e.getMessage());
                            }
                            handler.sendMessage(handler.obtainMessage());
                        }
                    }
                    );
            Servicethread.start();
        }


 static class MyHandler extends Handler{
                MyActiviy parentActivity;
                @Override
                public void handleMessage(Message msg){
                    // Update your UI here

                    }
                }

                MyHandler(MyActiviy activity){
                    parentActivity = activity;
                }
            }

MyHandler handler = new MyHandler(this);