在onReceive之后保持BroadcastReceiver活着

时间:2017-12-21 14:56:15

标签: android broadcastreceiver

我有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");
    }

}

1 个答案:

答案 0 :(得分:1)

您的PhoneCallReceiver不应该有MediaRecorder。它应该委托给具有MediaRecorder的前台服务。该服务可以保持稳定。通过比较,清单中注册的BroadcastReceiver仅适用于onReceive()次通话。