我发现了很多关于这个问题的问题,但我根本不清楚。 我想开发和应用程序,以便它可以记录任何拨出电话和来电。我在下面编写了这段代码,但它没有用。请帮忙详细解释。首先谢谢。
import java.io.File;
import java.io.IOException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class serviceBroadcast extends BroadcastReceiver {
Context mycontext;
final MediaRecorder recorder = new MediaRecorder();
public void onReceive(Context context, Intent intent) {
mycontext=context;
try {
// TELEPHONY MANAGER class object to register one listner
TelephonyManager tmgr = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
//Create Listner
TeleListener PhoneListener = new TeleListener();
// Register listener for LISTEN_CALL_STATE
tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
Log.e("Phone Receive Error", " " + e);
}
}
class TeleListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
StopRecording();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
startRecording();
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
default:
break;
}
}
}
public void startRecording(){
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(Environment.getExternalStorageDirectory()+ "/RecordMyVoice.mp4");
try {
recorder.prepare();
Log.i(this.getClass().getName(), "Prepared");
} catch (IllegalStateException e) {
e.printStackTrace();
Log.i(this.getClass().getName(), "ERR 1");
} catch (IOException e) {
e.printStackTrace();
Log.i(this.getClass().getName(), "ERR 2");
}
recorder.start();
}
public void StopRecording(){
recorder.stop();
recorder.release();
Log.i(this.getClass().getName(), "Stop Recording");
}
}
}
答案 0 :(得分:0)
也许这个答案没有解决你的问题,但它很渴望发表评论。没有看到Logcat很难说,为什么你得到一个异常,但有一点我看到,它可能会给你的release()调用错误。因此,如果您在MediaRecorder对象上调用release(),它将处于null状态,之后无法使用。所以问题是,你打电话给
final MediaRecorder recorder = new MediaRecorder();
一开始。制作MediaRecorder Global
是一种更好的做法 private MediaRecorder recorder=null;
并在startRecording()方法中创建Object:
private void startRecording(){
recorder = new MediaRecorder();
.
.
.
}
另外,不要忘记在清单中设置权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>