Reputation: 695
I have CallReceiver extends BroadcastReceiver
class which records phone calls via MediaRecorder
instance.
The problem is each time my service receives intent new instance of PhoneCallReceiver
is created with unitialized recorder.
Therefore I can't stop recording.Of course I can store recorder instance in the static variable but this is dirty hack.
I believe there must be way to keep service alive
Here is my receiver class:
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");
}
}
Upvotes: 0
Views: 38
Reputation: 1006859
Your PhoneCallReceiver
should not have a MediaRecorder
. It should delegate to a foreground service that has a MediaRecorder
. The service can remain stable. A BroadcastReceiver
registered in the manifest lives for just one onReceive()
call, by way of comparison.
Upvotes: 1