我想启动服务并录制音频,然后关闭活动,但保持录制,然后打开活动并停止录制。
这是我的服务:
public class RecorderService extends Service {
private Thread mThread;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mThread = new Thread(new Runnable() {
@Override
public void run() {
startRecording();
}
});
mThread.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
mThread = null;
super.onDestroy();
}
}
这是我启动和停止服务的代码:
Button recordAudioButton = (Button) findViewById(R.id.recordAudioButton);
recordAudioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(new Intent(getApplicationContext(), RecorderService.class));
}
});
Button buttonPLay = (Button) findViewById(R.id.buttonPLay);
buttonPLay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(new Intent(getApplicationContext(), RecorderService.class));
}
});
它开始但是当我停止服务时它不会停止。我做错了什么?
答案 0 :(得分:1)
问题在于,虽然您设置了mThread = null;
,但您还需要先停止它。
有关停止线程的更多详细信息,请参阅android best and safe way to stop thread。
对于您的示例,请尝试将onStartCommand
和onDestory
更改为:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mThread = new Thread(new Runnable() {
@Override
public void run() {
if (Thread.currentThread().isInterrupted()) {
return;
}
startRecording();
}
});
mThread.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
mThread.interrupt();
mThread = null;
super.onDestroy();
}