我有一个扩展服务并实现runnable的类,该服务收集噪声样本并且不同的活动绑定到它。我遇到的问题是,当我启动一个活动,在刚刚解除服务的另一个活动之后立即绑定它,那么我没有得到任何声音读数。
(如果我在to binding之间有非约束性活动,则它有效)
服务:
...........
...........
public class NoiseService extends Service implements Runnable{
private static volatile boolean isRunning = false;
.....
.....
private final Messenger mMessenger = new Messenger(new IncomingHandler());
@Override
public void onCreate(){
super.onCreate();
}
@Override
public void onDestroy(){
Log.d("SERVICE", "DESTROY");
synchronized (syncObject) {
isRunning = false;
}
super.onDestroy();
}
//Called from the Actons (Main Action and Calibrate)
@Override
public IBinder onBind(Intent arg0) {
Log.d("SERVICE", "BIND");
synchronized (syncObject) {
if(!isRunning){
isRunning = true;
serviceThread = new Thread(this);
serviceThread.start();
}
}
return mMessenger.getBinder();
}
public void run() {
Log.d("SERVICE", "START RUN");
BUFFSIZE = AudioRecord.getMinBufferSize(
FREQUENCY,
CHANNEL,
ENCODING);
if(BUFFSIZE <= 0) {
BUFFSIZE = 1024;
}
mRecordInstance = new AudioRecord(
MediaRecorder.AudioSource.VOICE_RECOGNITION,
FREQUENCY, CHANNEL,
ENCODING, BUFFSIZE*2);
// this is for the fast mode
BUFFSIZE = AudioRecord.getMinBufferSize(
FREQUENCY,
CHANNEL,
ENCODING)*2;
mRecordInstance.startRecording();
readCalibValue();
long timeToSleep = 0;
double splValue = 0.0;
double rmsValue = 0.0;
while(serviceThread == Thread.currentThread() && isRunning){
int SIZE = BUFFSIZE;
short[] tempBuffer = new short[SIZE];
mRecordInstance.read(tempBuffer, 0, SIZE);
for (int i = 0; i < SIZE - 1; i++) {
rmsValue += tempBuffer[i] * tempBuffer[i];
}
.....
do stuff
......
}
mRecordInstance.stop();
Log.d("SERVICE", "STOP RUN");
}
class IncomingHandler extends Handler { // Handler of incoming messages from clients.
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
synchronized (mClients){
mClients.add(msg.replyTo);
}
break;
case MSG_UNREGISTER_CLIENT:
synchronized (mClients) {
mClients.remove(msg.replyTo);
if(mClients.isEmpty()){
synchronized (syncObject) {
isRunning = false;
}
}
}
break;
default:
super.handleMessage(msg);
}
}
}
}
我无法弄清楚为什么会这样,除了While循环dos在新服务启动之前没有结束但是我不明白为什么这应该重要......