Comment enregistrer des appels téléphoniques dans Android?

Je veux créer une application qui enregistre les appels entrants et sortants et qui s’exécute automatiquement lorsque l’utilisateur reçoit ou effectue un appel.

Ok, pour cela, vous devez tout d’abord utiliser Device Policy Manager, et vous devez configurer votre périphérique d’administration. Après cela, vous devez créer un récepteur BroadCast et un service. Je poste le code ici et son bon fonctionnement.

Activité principale:

public class MainActivity extends Activity { private static final int REQUEST_CODE = 0; private DevicePolicyManager mDPM; private ComponentName mAdminName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // Initiate DevicePolicyManager. mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mAdminName = new ComponentName(this, DeviceAdminDemo.class); if (!mDPM.isAdminActive(mAdminName)) { Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application."); startActivityForResult(intent, REQUEST_CODE); } else { // mDPM.lockNow(); // Intent intent = new Intent(MainActivity.this, // TrackDeviceService.class); // startService(intent); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (REQUEST_CODE == requestCode) { Intent intent = new Intent(MainActivity.this, TService.class); startService(intent); } } } 

// Classe DeviceAdminDemo

 public class DeviceAdminDemo extends DeviceAdminReceiver { @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); } public void onEnabled(Context context, Intent intent) { }; public void onDisabled(Context context, Intent intent) { }; } 

// Classe TService

 public class TService extends Service { MediaRecorder recorder; File audiofile; Ssortingng name, phonenumber; Ssortingng audio_format; public Ssortingng Audio_Type; int audioSource; Context context; private Handler handler; Timer timer; Boolean offHook = false, ringing = false; Toast toast; Boolean isOffHook = false; private boolean recordstarted = false; private static final Ssortingng ACTION_IN = "android.intent.action.PHONE_STATE"; private static final Ssortingng ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL"; private CallBr br_call; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { Log.d("service", "destroy"); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // final Ssortingng terminate =(Ssortingng) // intent.getExtras().get("terminate");// // intent.getSsortingngExtra("terminate"); // Log.d("TAG", "service started"); // // TelephonyManager telephony = (TelephonyManager) // getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager // // object // CustomPhoneStateListener customPhoneListener = new // CustomPhoneStateListener(); // telephony.listen(customPhoneListener, // PhoneStateListener.LISTEN_CALL_STATE); // context = getApplicationContext(); final IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_OUT); filter.addAction(ACTION_IN); this.br_call = new CallBr(); this.registerReceiver(this.br_call, filter); // if(terminate != null) { // stopSelf(); // } return START_NOT_STICKY; } public class CallBr extends BroadcastReceiver { Bundle bundle; Ssortingng state; Ssortingng inCall, outCall; public boolean wasRinging = false; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_IN)) { if ((bundle = intent.getExtras()) != null) { state = bundle.getSsortingng(TelephonyManager.EXTRA_STATE); if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { inCall = bundle.getSsortingng(TelephonyManager.EXTRA_INCOMING_NUMBER); wasRinging = true; Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show(); } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) { if (wasRinging == true) { Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show(); Ssortingng out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date()); File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1"); if (!sampleDir.exists()) { sampleDir.mkdirs(); } Ssortingng file_name = "Record"; try { audiofile = File.createTempFile(file_name, ".amr", sampleDir); } catch (IOException e) { e.printStackTrace(); } Ssortingng path = Environment.getExternalStorageDirectory().getAbsolutePath(); recorder = new MediaRecorder(); // recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL); recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(audiofile.getAbsolutePath()); try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } recorder.start(); recordstarted = true; } } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) { wasRinging = false; Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show(); if (recordstarted) { recorder.stop(); recordstarted = false; } } } } else if (intent.getAction().equals(ACTION_OUT)) { if ((bundle = intent.getExtras()) != null) { outCall = intent.getSsortingngExtra(Intent.EXTRA_PHONE_NUMBER); Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show(); } } } } } 

// Autorisation dans le fichier manifeste

      

//my_admin.xml

      

// Déclare la chose suivante dans le manifeste:

Déclarez la classe DeviceAdminDemo à manifester:

            

Le code ci-dessous fonctionne pour moi pour enregistrer un appel téléphonique sortant

 //Call Recording varibales private static final Ssortingng AUDIO_RECORDER_FILE_EXT_3GP = ".3gp"; private static final Ssortingng AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4"; private static final Ssortingng AUDIO_RECORDER_FOLDER = "AudioRecorder"; private MediaRecorder recorder = null; private int currentFormat = 0; private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP }; private Ssortingng file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP }; AudioManager audioManager; 

// met cette méthode en dehors de la méthode oncreate ()

 private Ssortingng getFilename() { Ssortingng filepath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filepath, AUDIO_RECORDER_FOLDER); if (!file.exists()) { file.mkdirs(); } return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]); } private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() { @Override public void onError(MediaRecorder mr, int what, int extra) { Toast.makeText(CallActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show(); } }; private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() { @Override public void onInfo(MediaRecorder mr, int what, int extra) { Toast.makeText(CallActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT) .show(); } }; 

// sous une partie du code pour que votre appareil soit sur le haut-parleur

  audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(true); 

// sous la partie de code pour commencer l’enregistrement

 recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(output_formats[currentFormat]); //recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(getFilename()); recorder.setOnErrorListener(errorListener); recorder.setOnInfoListener(infoListener); try { recorder.prepare(); recorder.start(); } catch (IllegalStateException e) { Log.e("REDORDING :: ",e.getMessage()); e.printStackTrace(); } catch (IOException e) { Log.e("REDORDING :: ",e.getMessage()); e.printStackTrace(); } 

// Pour arrêter l’enregistrement et ne pas oublier de mettre le haut-parleur hors tension pendant la fin de l’appel ou l’arrêt

 audioManager.setSpeakerphoneOn(false); try{ if (null != recorder) { recorder.stop(); recorder.reset(); recorder.release(); recorder = null; } }catch(RuntimeException stopException){ } 

Et donner la permission de manifester le fichier,

       

Je voudrais commenter à ce sujet, même difficile Son ancien poste. Donc, fondamentalement, je veux combiner 2 réponses, une de cet article et une d’un autre que j’ai lu, je ne connais pas l’auteur de ce message, alors s’il vous plaît désolé d’utiliser vos méthodes.

Alors, voici mes cours pour obtenir le résultat souhaité:

  public class StartActivity extends Activity { public static final int REQUEST_CODE = 5912; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PackageManager p = getPackageManager(); ComponentName componentName = new ComponentName(this, StartActivity.class); // activity which is first time open in manifiest file which is declare as  p.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); startService(new Intent(this, StartService.class)); startService(new Intent(this, SmsOutgoingService.class)); try { // Initiate DevicePolicyManager. DevicePolicyManager mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName mAdminName = new ComponentName(this, DeviceAdminReciever.class); if (!mDPM.isAdminActive(mAdminName)) { Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application."); startActivityForResult(intent, REQUEST_CODE); } else { mDPM.lockNow(); finish(); // Intent intent = new Intent(MainActivity.this, // TrackDeviceService.class); // startService(intent); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (REQUEST_CODE == requestCode) { startService(new Intent(StartActivity.this, TService.class)); finish(); } super.onActivityResult(requestCode, resultCode, data); } } 

Et ma classe TService :

  public class TService extends Service { private MediaRecorder recorder; private File audiofile; private boolean recordstarted = false; private static final Ssortingng ACTION_IN = "android.intent.action.PHONE_STATE"; private static final Ssortingng ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL"; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { Log.d("service", "destroy"); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("StartService", "TService"); final IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_OUT); filter.addAction(ACTION_IN); this.registerReceiver(new CallReceiver(), filter); return super.onStartCommand(intent, flags, startId); } private void startRecording() { File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1"); if (!sampleDir.exists()) { sampleDir.mkdirs(); } Ssortingng file_name = "Record"; try { audiofile = File.createTempFile(file_name, ".amr", sampleDir); } catch (IOException e) { e.printStackTrace(); } Ssortingng path = Environment.getExternalStorageDirectory().getAbsolutePath(); recorder = new MediaRecorder(); // recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL); recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(audiofile.getAbsolutePath()); try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } recorder.start(); recordstarted = true; } private void stopRecording() { if (recordstarted) { recorder.stop(); recordstarted = false; } } public abstract class PhonecallReceiver extends BroadcastReceiver { //The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations private int lastState = TelephonyManager.CALL_STATE_IDLE; private Date callStartTime; private boolean isIncoming; private Ssortingng savedNumber; //because the passed incoming is only valid in ringing @Override public void onReceive(Context context, Intent intent) { // startRecording(); //We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number. if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) { savedNumber = intent.getExtras().getSsortingng("android.intent.extra.PHONE_NUMBER"); } else { Ssortingng stateStr = intent.getExtras().getSsortingng(TelephonyManager.EXTRA_STATE); Ssortingng number = intent.getExtras().getSsortingng(TelephonyManager.EXTRA_INCOMING_NUMBER); int state = 0; if (stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) { state = TelephonyManager.CALL_STATE_IDLE; } else if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) { state = TelephonyManager.CALL_STATE_OFFHOOK; } else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) { state = TelephonyManager.CALL_STATE_RINGING; } onCallStateChanged(context, state, number); } } //Derived classes should override these to respond to specific events of interest protected abstract void onIncomingCallReceived(Context ctx, Ssortingng number, Date start); protected abstract void onIncomingCallAnswered(Context ctx, Ssortingng number, Date start); protected abstract void onIncomingCallEnded(Context ctx, Ssortingng number, Date start, Date end); protected abstract void onOutgoingCallStarted(Context ctx, Ssortingng number, Date start); protected abstract void onOutgoingCallEnded(Context ctx, Ssortingng number, Date start, Date end); protected abstract void onMissedCall(Context ctx, Ssortingng number, Date start); //Deals with actual events //Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up //Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up public void onCallStateChanged(Context context, int state, Ssortingng number) { if (lastState == state) { //No change, debounce extras return; } switch (state) { case TelephonyManager.CALL_STATE_RINGING: isIncoming = true; callStartTime = new Date(); savedNumber = number; onIncomingCallReceived(context, number, callStartTime); break; case TelephonyManager.CALL_STATE_OFFHOOK: //Transition of ringing->offhook are pickups of incoming calls. Nothing done on them if (lastState != TelephonyManager.CALL_STATE_RINGING) { isIncoming = false; callStartTime = new Date(); startRecording(); onOutgoingCallStarted(context, savedNumber, callStartTime); } else { isIncoming = true; callStartTime = new Date(); startRecording(); onIncomingCallAnswered(context, savedNumber, callStartTime); } break; case TelephonyManager.CALL_STATE_IDLE: //Went to idle- this is the end of a call. What type depends on previous state(s) if (lastState == TelephonyManager.CALL_STATE_RINGING) { //Ring but no pickup- a miss onMissedCall(context, savedNumber, callStartTime); } else if (isIncoming) { stopRecording(); onIncomingCallEnded(context, savedNumber, callStartTime, new Date()); } else { stopRecording(); onOutgoingCallEnded(context, savedNumber, callStartTime, new Date()); } break; } lastState = state; } } public class CallReceiver extends PhonecallReceiver { @Override protected void onIncomingCallReceived(Context ctx, Ssortingng number, Date start) { Log.d("onIncomingCallReceived", number + " " + start.toSsortingng()); } @Override protected void onIncomingCallAnswered(Context ctx, Ssortingng number, Date start) { Log.d("onIncomingCallAnswered", number + " " + start.toSsortingng()); } @Override protected void onIncomingCallEnded(Context ctx, Ssortingng number, Date start, Date end) { Log.d("onIncomingCallEnded", number + " " + start.toSsortingng() + "\t" + end.toSsortingng()); } @Override protected void onOutgoingCallStarted(Context ctx, Ssortingng number, Date start) { Log.d("onOutgoingCallStarted", number + " " + start.toSsortingng()); } @Override protected void onOutgoingCallEnded(Context ctx, Ssortingng number, Date start, Date end) { Log.d("onOutgoingCallEnded", number + " " + start.toSsortingng() + "\t" + end.toSsortingng()); } @Override protected void onMissedCall(Context ctx, Ssortingng number, Date start) { Log.d("onMissedCall", number + " " + start.toSsortingng()); // PostCallHandler postCallHandler = new PostCallHandler(number, "janskd" , "") } } } 

dans la classe TService , vous trouverez la classe CallReceiever qui CallReceiever tout ce dont vous avez besoin de l’appel. Vous pouvez append des parameters selon votre volonté, mais le point principal est important.

À partir de votre service MainActvitiy, le service qui démarrera votre récepteur. Si vous souhaitez enregistrer directement le contenu du récepteur, vous obtiendrez des erreurs. Vous devez donc enregistrer le destinataire du service. Après cela, vous pouvez appeler le début de l’enregistrement et terminer l’enregistrement où vous voulez. return super.onStartCommand(intent, flags, startId); appel return super.onStartCommand(intent, flags, startId); aura ce service pour plus d’un appel, alors gardez cela à l’esprit.

Enfin, le fichier AndroidManifest.xml :

                                  

Alors ça y est, ça fonctionne parfaitement avec mon Samsung Galaxy S6 Edge +, je l’ai testé sur Galaxy Note 4 et sur Samsung J5, un grand merci aux auteurs de ce post et au post concernant les appels téléphoniques reçus.

La réponse de pratt est un peu incomplète, car lorsque vous redémarrez votre appareil, votre application va s’arrêter, l’enregistrement s’arrête, son utilisation devient inutile.

im append une ligne qui copie dans votre projet pour le travail complet de réponse de Pratt.

           

mettre ce code dans onReceive de DeviceAdminDemo

 @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); context.stopService(new Intent(context, TService.class)); Intent myIntent = new Intent(context, TService.class); context.startService(myIntent); } 

La réponse acceptée est parfaite, sauf qu’elle n’enregistre pas les appels sortants. Notez que pour les appels sortants, il n’est pas possible (aussi proche que possible de parcourir de nombreux messages) pour détecter la réponse à l’appel (si quelqu’un peut trouver un moyen autre que de parcourir les notifications ou les journaux, faites le moi savoir). La solution la plus simple consiste à commencer à enregistrer immédiatement lorsque l’appel sortant est placé et à arrêter l’enregistrement lorsque IDLE est détecté. Il suffit d’append la même classe que ci-dessus avec l’enregistrement sortant de cette manière pour être complet:

 private void startRecord(Ssortingng seed) { Ssortingng out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date()); File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1"); if (!sampleDir.exists()) { sampleDir.mkdirs(); } Ssortingng file_name = "Record" + seed; try { audiofile = File.createTempFile(file_name, ".amr", sampleDir); } catch (IOException e) { e.printStackTrace(); } Ssortingng path = Environment.getExternalStorageDirectory().getAbsolutePath(); recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(audiofile.getAbsolutePath()); try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } recorder.start(); recordstarted = true; } @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_IN)) { if ((bundle = intent.getExtras()) != null) { state = bundle.getSsortingng(TelephonyManager.EXTRA_STATE); if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { inCall = bundle.getSsortingng(TelephonyManager.EXTRA_INCOMING_NUMBER); wasRinging = true; Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show(); } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) { if (wasRinging == true) { Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show(); startRecord("incoming"); } } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) { wasRinging = false; Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show(); if (recordstarted) { recorder.stop(); recordstarted = false; } } } } else if (intent.getAction().equals(ACTION_OUT)) { if ((bundle = intent.getExtras()) != null) { outCall = intent.getSsortingngExtra(Intent.EXTRA_PHONE_NUMBER); Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show(); startRecord("outgoing"); if ((bundle = intent.getExtras()) != null) { state = bundle.getSsortingng(TelephonyManager.EXTRA_STATE); if (state != null) { if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) { wasRinging = false; Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show(); if (recordstarted) { recorder.stop(); recordstarted = false; } } } } } } }