想知道是否有人可以帮我解决Android上的后台线程问题。
我有一段代码可以从设备的麦克风中录制,然后播放通过耳机录制的内容(在1.5上)。
我试图在一个线程中运行它,但是没有成功将它作为后台线程运行。
目前它运行并锁定活动,以便所有发生的事情都是线程正在运行且UI被锁定或似乎挂起。
以下是我尝试过的最新方式:
public class LoopProg extends Activity {
boolean isRecording; //currently not used
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AudioManager audio_service = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audio_service.setSpeakerphoneOn(false);
audio_service.setMode(AudioManager.MODE_IN_CALL);
audio_service.setRouting(AudioManager.MODE_NORMAL,
AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
Record record = new Record();
record.run();
}
public class Record extends Thread
{
static final int bufferSize = 200000;
final short[] buffer = new short[bufferSize];
short[] readBuffer = new short[bufferSize];
public void run() {
isRecording = true;
android.os.Process.setThreadPriority
(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
int buffersize = AudioRecord.getMinBufferSize(11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
buffersize);
AudioTrack atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
buffersize,
AudioTrack.MODE_STREAM);
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
atrack.setPlaybackRate(11025);
byte[] buffer = new byte[buffersize];
arec.startRecording();
atrack.play();
while(isRecording) {
arec.read(buffer, 0, buffersize);
atrack.write(buffer, 0, buffer.length);
}
arec.stop();
atrack.stop();
isRecording = false;
}
}
}
我想知道是否有人可以指导我如何将其变成后台线程?或者或许有人指出我可能错过的一些可能相关的教程?
提前致谢
答案 0 :(得分:14)
答案 1 :(得分:3)
你不应该调用Thread.run,调用Thread.start
public void run()
如果这个帖子是 使用单独的Runnable构造 运行对象,然后运行Runnable 调用object的run方法; 否则,这种方法什么都不做 并返回。