2

我正在制作一个 android 应用程序,我想maxDbRecorded在类的属性Measure更改时更新标签。所以我在我的活动中实现了一个 PropertyChangeListener。

public class AndroidCalibrationTestActivity extends Activity implements PropertyChangeListener {
   private Recorder recorder;
   private Thread recorderThread;
   private Measure measures;
   private TextView numberOfMaxDecibels;

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       numberOfMaxDecibels = (TextView)findViewById(R.id.txtNumberOfMaxDecibels); 

       measures = new Measure();
       measures.addPropertyChangeListener(this);

       recorderThread = new Thread((Runnable) Recorder.getInstance().runRecorder); 
       recorderThread.start();
   }

   public void propertyChange(PropertyChangeEvent event) {
        numberOfMaxDecibels.setText(event.getNewValue() + "");  
   }          
}

现在我想maxDbRecorded在我的线程中设置 from 的值。以便 textview numberOfMaxDecibels 更新。

public class Measure {
    private double maxDbRecorded;   

    private PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    public Measure() {  
    }

    //Getters and setters       
    public double getMaxDbRecorded() {  
        return maxDbRecorded;
    }
    public void setMaxDbRecorded(double maxDbRecorded) {
            double oldValue = this.maxDbRecorded;
            this.maxDbRecorded = maxDbRecorded;
            //Fires a property change event
            pcs.firePropertyChange("maxDbRecorded", oldValue, maxDbRecorded);           
    }

    //To let classes subscribe for property changed listener
    public void addPropertyChangeListener(PropertyChangeListener listener){
        pcs.addPropertyChangeListener("maxDbRecorded", listener);
    }
}

在类 Recorder 中,我有我设置的线程maxDbRecorded,但 PropertyChanged 事件没有被触发。如果我maxDbRecorded直接从 Activity 设置它确实有效。

public class Recorder {
    protected Measure m;

    private Recorder() {
        m = new Measure();
    }

    public static Recorder getInstance() {
        if(instance == null){
            instance = new Recorder();
        }
        return instance;
    }

    Runnable runRecorder = new Runnable() { 
        public void run() {
             startRecording();  
        }
    };

    public void startRecording() {
        //Here happens some recording stuff
        double maxDB;
        m.setMaxDbRecorded(maxDB);
    }     
}

我还尝试在我的 Activity 中创建一个 Measure 对象并将此实例提供给 Recorder 线程。这给出了一个错误: $CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触及它的视图。

4

1 回答 1

1

您应该使用 android 处理程序类通过它向 ui 线程发布您的调用。

检查:http ://www.vogella.com/articles/AndroidPerformance/article.html

于 2012-04-26T21:06:42.777 回答