我有CallReceiver extends BroadcastReceiver
通过MediaRecorder
实例记录电话的课程。
问题是每次我的服务收到意图时,PhoneCallReceiver
都会使用未初始化的记录器创建新实例。
因此我不能停止记录。当然我可以将记录器实例存储在静态变量中,但这是肮脏的黑客。
我相信一定有办法让服务保持活力
这是我的接收器类:
public class CallReceiver extends PhoneCallReceiver {
private static VoiceRecorder recorder; // VoiceRecorder stores MediaRecorder instance
@Override
protected void onIncomingCallReceived(Context ctx, String number, Date start)
{
Log.d("phone","onIncomingCallReceived");
}
@Override
protected void onIncomingCallAnswered(Context ctx, String number, Date start)
{
Log.d("phone","onIncomingCallAnswered");
MainActivity.recorder=new VoiceRecorder("incoming_"+number);
try {
MainActivity.recorder.start();
} catch (IOException e) {
Log.d("phone error",e.getLocalizedMessage());
e.printStackTrace();
}
}
@Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
{
Log.d("phone","onIncomingCallEnded");
if (MainActivity.recorder!=null) {
try {
MainActivity.recorder.stop();
} catch (Exception e) {
Log.d("phone record error",e.getLocalizedMessage());
e.printStackTrace();
}
MainActivity.recorder=null;
}
}
@Override
protected void onOutgoingCallStarted(Context ctx, String number, Date start)
{
Log.d("phone","onOutgoingCallStarted "+MainActivity.recorder);
MainActivity.recorder=new VoiceRecorder("outgoing_"+number);
try {
MainActivity.recorder.start();
} catch (IOException e) {
Log.d("phone error",e.getLocalizedMessage());
e.printStackTrace();
}
}
@Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end)
{
Log.d("phone","onOutgoingCallEnded "+MainActivity.recorder);
if (MainActivity.recorder!=null) {
try {
MainActivity.recorder.stop();
} catch (IOException e) {
e.printStackTrace();
}
MainActivity.recorder=null;
}
}
@Override
protected void onMissedCall(Context ctx, String number, Date start)
{
Log.d("phone","onMissedCall");
}
}
你PhoneCallReceiver
不应该有一个MediaRecorder
. 它应该委托给具有MediaRecorder
. 服务可以保持稳定。作为比较BroadcastReceiver
,在清单中注册的一个只存在一次onReceive()
调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句