2017-12-21 19 views
0

私はMediaRecorderのインスタンスを介して電話を記録するCallReceiver extends BroadcastReceiverクラスを持っています。
私のサービスがインテントを受け取るたびに、問題はユニット化されたレコーダーを使用してPhoneCallReceiverの新しいインスタンスが作成されます。
したがって、私は記録を停止することはできません。もちろん、私は静的変数にレコーダインスタンスを格納することができますが、これは汚れたハックです。
私はここに私のレシーバ・クラスがある
生きサービスを維持する方法がなければならないと信じて:onReceiveの後にBroadcastReceiverを生かしてください

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

} 
+0

あなたの 'PhoneCallReceiver'は' MediaRecorder'を持つべきではありません。 'MediaRecorder'を持つフォアグラウンドサービスに委任すべきです。それを超えて、問題を示す[mcve]で質問を編集することができます。 – CommonsWare

+0

@CommonsWareので、この場合静的変数はOKですか?PS:投稿 – undefined

+0

を更新しました。 "この場合、静的変数は大丈夫ですか?" - いいえ。 「ここに私のサービスクラスがあります」 - それはサービスのようには見えません。これは 'BroadcastReceiver'と思われます。 – CommonsWare

答えて

1

あなたPhoneCallReceiverMediaRecorderを持つべきではありません。 MediaRecorderを持つフォアグラウンドサービスに委任する必要があります。サービスは安定したままです。比較のためにマニフェストに登録されているBroadcastReceiverは、ただ1つのonReceive()コールの間しか存在しません。

関連する問題