Android application development: code samples for phone monitoring and recording

  • 2020-06-01 10:58:06
  • OfStack

Execute in oncreate:


public void onCreate() {
  super.onCreate();
  Log.i("TAG", " The service is up ");
  //  Monitor the status of incoming calls 
  TelephonyManager telManager = (TelephonyManager) this
    .getSystemService(Context.TELEPHONY_SERVICE);
  //  registered 1 Three listeners monitor the status of the phone 
  telManager.listen(new MyPhoneStateListener(),
    PhoneStateListener.LISTEN_CALL_STATE);
}

Implement MyPhoneStateListener:

private class MyPhoneStateListener extends PhoneStateListener {
  MediaRecorder recorder;
  File audioFile;
  String phoneNumber;
  public void onCallStateChanged(int state, String incomingNumber) {
   switch (state) {
   case TelephonyManager.CALL_STATE_IDLE: /*  No state at all  */
    if (recorder != null) {
     recorder.stop(); // Stop the recording 
     recorder.reset(); // reset 
     recorder.release(); // Burn complete 1 Resources must be released 
    }
    break;
   case TelephonyManager.CALL_STATE_OFFHOOK: /*  When I pick up the phone  */
    try {
     recorder = new MediaRecorder();
     recorder.setAudioSource(MediaRecorder.AudioSource.MIC); //  Set the audio acquisition source 
     recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // Content output format 
     recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // Audio coding mode 
     // recorder.setOutputFile("/sdcard/myvoice.amr");
     audioFile = new File(
       Environment.getExternalStorageDirectory(),
       phoneNumber + "_" + System.currentTimeMillis()
         + ".3gp");
     recorder.setOutputFile(audioFile.getAbsolutePath());
     Log.i("TAG", audioFile.getAbsolutePath());
     recorder.prepare(); // Expected to prepare 
     recorder.start();
    } catch (IllegalStateException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
    break;
   case TelephonyManager.CALL_STATE_RINGING: /*  When the call came in  */
    phoneNumber = incomingNumber;
    break;
   default:
    break;
   }
   super.onCallStateChanged(state, incomingNumber);
  }
 }

By following the two corresponding steps above, the phone can be monitored by server in the following states: CALL_STATE_IDLE stateless (that is, idle), CALL_STATE_OFFHOOK connected (that is, suspended), and CALL_STATE_RINGING incoming (that is, when a call is called).

Attachment: sample code for taking, recording and recording Android


package com.cons.dcg.collect;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import android.app.*;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.*;
import android.widget.*;
public class RecordActivity extends Activity implements OnClickListener {
        private static final int RESULT_CAPTURE_IMAGE = 1;//  Take photos of requestCode
        private static final int REQUEST_CODE_TAKE_VIDEO = 2;//  Of or relating to a camera requestCode
        private static final int RESULT_CAPTURE_RECORDER_SOUND = 3;//  The recording of the requestCode

        private String strImgPath = "";//  Absolute path to photo file 
        private String strVideoPath = "";//  The absolute path to the video file 
        private String strRecorderPath = "";//  The absolute path to the recording file 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                this.setContentView(R.layout.problem_report);
        }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                switch (requestCode) {
                case RESULT_CAPTURE_IMAGE:// Taking pictures 
                        if (resultCode == RESULT_OK) {
                                Toast.makeText(this, strImgPath, Toast.LENGTH_SHORT).show();
                        }
                        break;
                case REQUEST_CODE_TAKE_VIDEO:// Shoot video 
                        if (resultCode == RESULT_OK) {
                                Uri uriVideo = data.getData();
                                Cursor cursor=this.getContentResolver().query(uriVideo, null, null, null, null);
                                if (cursor.moveToNext()) {
                                        /** _data : the absolute path to the file   . _display_name : the name of the file  */
                                        strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
                                        Toast.makeText(this, strVideoPath, Toast.LENGTH_SHORT).show();
                                }
                        }
                        break;
                case RESULT_CAPTURE_RECORDER_SOUND:// The recording 
                        if (resultCode == RESULT_OK) {
                                Uri uriRecorder = data.getData();
                                Cursor cursor=this.getContentResolver().query(uriRecorder, null, null, null, null);
                                if (cursor.moveToNext()) {
                                        /** _data : the absolute path to the file   . _display_name : the name of the file  */
                                        strRecorderPath = cursor.getString(cursor.getColumnIndex("_data"));
                                        Toast.makeText(this, strRecorderPath, Toast.LENGTH_SHORT).show();
                                }
                        } 
                        break;
                }
        }

       
        /**
         *  A camera 
         */
        private void cameraMethod() {
                Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                strImgPath = Environment.getExternalStorageDirectory().toString() + "/CONSDCGMPIC/";// A folder to store your photos in 
                String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";// Photo named 
                File out = new File(strImgPath);
                if (!out.exists()) {
                        out.mkdirs();
                }
                out = new File(strImgPath, fileName);
                strImgPath = strImgPath + fileName;// The absolute path of the photo 
                Uri uri = Uri.fromFile(out);
                imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(imageCaptureIntent, RESULT_CAPTURE_IMAGE);
        }
        /**
         *  Shoot video 
         */
        private void videoMethod() {
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
        }
        /**
         *  Recording function 
         */
        private void soundRecorderMethod() {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("audio/amr");
                startActivityForResult(intent, RESULT_CAPTURE_RECORDER_SOUND);
        }
        /**
         *  Prompt information 
         * @param text
         * @param duration
         */
        private void showToast(String text, int duration) {
                Toast.makeText(ProblemReport.this, text, duration).show();
        }
}


Related articles: