在 onReceive 之后保持 BroadcastReceiver 存活

keep BroadcastReceiver alive after onReceive

我有 CallReceiver extends BroadcastReceiver class 记录了通过 MediaRecorder 实例进行的 phone 调用。
问题是每次我的服务收到 intent 的新实例PhoneCallReceiver 是使用单元化记录器创建的。
因此我无法停止 recording.Of 当然我可以将记录器实例存储在静态变量中,但这是肮脏的 hack。
我相信必须有办法让服务保持活跃
这是我的接收器 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");
    }

}

您的 PhoneCallReceiver 不应有 MediaRecorder。它应该委托给具有 MediaRecorder 的前台服务。服务可以保持稳定。作为比较,在清单中注册的 BroadcastReceiver 只存在一次 onReceive() 调用。