在onReceive之后保持BroadcastReceiver活着
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在onReceive之后保持BroadcastReceiver活着相关的知识,希望对你有一定的参考价值。
我有CallReceiver extends BroadcastReceiver
类,通过MediaRecorder
实例记录电话。
问题是每次我的服务收到意图PhoneCallReceiver
的新实例是用unitialized recorder创建的。
因此我无法停止录制。当然我可以将录像机实例存储在静态变量中,但这是脏黑客。
我相信必须有办法让服务保持活力
这是我的接收器类:
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()
电话。
以上是关于在onReceive之后保持BroadcastReceiver活着的主要内容,如果未能解决你的问题,请参考以下文章
Android学习笔记(十七) BroadcastReceiver