【发布时间】:2014-01-04 13:13:42
【问题描述】:
我的线程的 run() 方法在 try-catch 块中有 while 循环,如下所示:
try{
while(true){
// some code here
if(condition)
break;
else
//more code here
}
}catch(Exception e){..}
我猜代码没有进入无限循环,因为:
我的 if 条件保证会在一些迭代后导致循环中断。
由于catch块在while循环外,所以while循环内的任何异常都会导致循环中断。
我一启动线程,应用就崩溃了。
我已经浏览了这个post,但仍然不清楚上面的代码有什么问题。
这是我完整的运行方法:
private static final int AUDIO_SOURCE=MediaRecorder.AudioSource.MIC;
private static final int SAMPLE_RATE_IN_HZ=44100;
private static final int CHANNEL_CONFIG=AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT=AudioFormat.ENCODING_PCM_16BIT;
public void run() {
//writing to AudioTrack object using 512kB buffer
int buffSize=512*1024; //512kb = 512*1024 B
byte[] buff=new byte[buffSize];
int fileSize=(int)outputFile.length(); //outputFile=.PCM file
int bytesRead=0,readCount=0;
FileInputStream fin=null;
try {
fin = new FileInputStream(outputFile);
}catch(Exception e){}
int TrackBufferSizeInBytes=android.media.AudioTrack.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG,AUDIO_FORMAT);
//create AudioTrack object
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC,SAMPLE_RATE_IN_HZ,CHANNEL_CONFIG,
AUDIO_FORMAT, TrackBufferSizeInBytes, AudioTrack.MODE_STREAM);
at.play();
try{
while(bytesRead<fileSize){
readCount=fin.read(buff,0,buffSize);
if(readCount==(-1)) // if EOF is reached
break;
else{
at.write(buff, 0, readCount); //write read bytes to Track
bytesRead+=readCount;
}
}
at.stop();
at.release();
at=null;
fin.close();
}catch(Exception e){}
}
请帮助我。提前致谢!
【问题讨论】:
-
如果一个异常被捕获,你直接进入 catch 块,你可以忘记你的循环。你发现了什么异常?你能 Log.e("TAG", "err", e);赶上?
-
你是在使用大量内存还是递归?
-
“应用程序崩溃” - 这表明日志中会有异常。这是什么?
-
@VM : 循环体有 read() 和 write() 操作。
-
@thumbmunkeys:不只是一个读写语句。
标签: android multithreading while-loop try-catch