Getting error on recorder.start() - android

I am new in android development. When i am recording a call in my service class the recorder.start() is getting IllegalStateException.Here is my Logcat:
java.lang.IllegalStateException.android.media.MediaRecorder.stop(Native Method)
my serivce class is:--
public class RecordService extends Service {
private MediaRecorder recorder = null;
private String phoneNumber = null;
private String fileName;
private boolean onCall = false;
private boolean recording = false;
private boolean silentMode = false;
private boolean onForeground = false;
private int currentFormat = 0;
private String AUDIO_RECORDER_FOLDER = "Testing_recording";
String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP3,
AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };
static final String AUDIO_RECORDER_FILE_EXT_MP3 = ".mp3";
static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
MediaRecorder.OutputFormat.THREE_GPP };
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Constants.TAG, "RecordService onStartCommand");
if (intent != null) {
int commandType = intent.getIntExtra("commandType", 0);
if (commandType != 0) {
if (commandType == Constants.RECORDING_ENABLED) {
Log.d(Constants.TAG, "RecordService RECORDING_ENABLED");
silentMode = intent.getBooleanExtra("silentMode", true);
if (!silentMode && phoneNumber != null && onCall
&& !recording)
commandType = Constants.STATE_START_RECORDING;
} else if (commandType == Constants.RECORDING_DISABLED) {
Log.d(Constants.TAG, "RecordService RECORDING_DISABLED");
silentMode = intent.getBooleanExtra("silentMode", true);
if (onCall && phoneNumber != null && recording)
commandType = Constants.STATE_STOP_RECORDING;
}
if (commandType == Constants.STATE_INCOMING_NUMBER) {
Log.d(Constants.TAG, "RecordService STATE_INCOMING_NUMBER");
startService();
if (phoneNumber == null)
phoneNumber = intent.getStringExtra("phoneNumber");
silentMode = intent.getBooleanExtra("silentMode", true);
} else if (commandType == Constants.STATE_CALL_START) {
Log.d(Constants.TAG, "RecordService STATE_CALL_START");
onCall = true;
if (phoneNumber != null && onCall
&& !recording) {
startService();
startRecording(intent);
}
} else if (commandType == Constants.STATE_CALL_END) {
Log.d(Constants.TAG, "RecordService STATE_CALL_END");
onCall = false;
phoneNumber = null;
stopAndReleaseRecorder();
recording = false;
stopService();
} else if (commandType == Constants.STATE_START_RECORDING) {
Log.d(Constants.TAG, "RecordService STATE_START_RECORDING");
if ( phoneNumber != null && onCall) {
startService();
startRecording(intent);
}
} else if (commandType == Constants.STATE_STOP_RECORDING) {
Log.d(Constants.TAG, "RecordService STATE_STOP_RECORDING");
stopAndReleaseRecorder();
recording = false;
}
}
}
return super.onStartCommand(intent, flags, startId);
}
/**
* in case it is impossible to record
*/
private void terminateAndEraseFile() {
Log.d(Constants.TAG, "RecordService terminateAndEraseFile");
stopAndReleaseRecorder();
recording = false;
// deleteFile();
}
private void stopService() {
Log.d(Constants.TAG, "RecordService stopService");
stopForeground(true);
onForeground = false;
this.stopSelf();
}
private void deletseFile() {
Log.d(Constants.TAG, "RecordService deleteFile");
FileHelper.deleteFile(fileName);
fileName = null;
}
private void stopAndReleaseRecorder() {
if (recorder == null)
return;
Log.d(Constants.TAG, "RecordService stopAndReleaseRecorder");
boolean recorderStopped = false;
boolean exception = false;
try {
recorder.stop();
recorderStopped = true;
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "IllegalStateException");
e.printStackTrace();
exception = true;
} catch (RuntimeException e) {
Log.e(Constants.TAG, "RuntimeException");
exception = true;
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
try {
recorder.reset();
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
try {
recorder.release();
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
recorder = null;
if (exception) {
// deleteFile();
}
if (recorderStopped) {
Toast toast = Toast.makeText(this,
this.getString(R.string.receiver_end_call),
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onDestroy() {
Log.d(Constants.TAG, "RecordService onDestroy");
stopAndReleaseRecorder();
stopService();
super.onDestroy();
}
private void startRecording(Intent intent) {
Log.d(Constants.TAG, "RecordService startRecording");
boolean exception = false;
recorder = new MediaRecorder();
try {
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK);
// recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// fileName = FileHelper.getFilename(phoneNumber);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
OnErrorListener errorListener = new OnErrorListener() {
public void onError(MediaRecorder arg0, int arg1, int arg2) {
Log.e(Constants.TAG, "OnErrorListener " + arg1 + "," + arg2);
terminateAndEraseFile();
}
};
recorder.setOnErrorListener(errorListener);
OnInfoListener infoListener = new OnInfoListener() {
public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
Log.e(Constants.TAG, "OnInfoListener " + arg1 + "," + arg2);
terminateAndEraseFile();
}
};
recorder.setOnInfoListener(infoListener);
recorder.prepare();
// Sometimes prepare takes some time to complete
Thread.sleep(2000);
try {
recorder.start();
} catch (Throwable t) {
t.printStackTrace();
Log.w("sf", t);
}
// recorder.start();
/*new Handler().postDelayed(new Runnable() {
public void run() {
// recorder.stop();
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
System.out.println("hello helloo");
recorder = null;
}
Log.e("Ho rha hai", "goodndnd");
}
}, 40000);*/
recording = true;
Log.d(Constants.TAG, "RecordService recorderStarted");
Toast.makeText(getApplicationContext(), "recording is strated ", 2000).show();
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "IllegalStateException");
e.printStackTrace();
exception = true;
} catch (IOException e) {
Log.e(Constants.TAG, "IOException");
e.printStackTrace();
exception = true;
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
if (exception) {
terminateAndEraseFile();
}
if (recording) {
Toast toast = Toast.makeText(this,
this.getString(R.string.receiver_start_call),
Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(this,
this.getString(R.string.record_impossible),
Toast.LENGTH_LONG);
toast.show();
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
public void onError(MediaRecorder mr, int what, int extra) {
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
public void onInfo(MediaRecorder mr, int what, int extra) {
}
};
private void startService() {
if (!onForeground) {
Log.d(Constants.TAG, "RecordService startService");
Intent intent = new Intent(this, MainActivity.class);
// intent.setAction(Intent.ACTION_VIEW);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(
getBaseContext(), 0, intent, 0);
Notification notification = new NotificationCompat.Builder(
getBaseContext())
.setContentTitle(
this.getString(R.string.notification_title))
.setTicker(this.getString(R.string.notification_ticker))
.setContentText(this.getString(R.string.notification_text))
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent).setOngoing(true)
.getNotification();
notification.flags = Notification.FLAG_NO_CLEAR;
startForeground(1337, notification);
onForeground = true;
}
}
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd_MMM_yy_HH_mm_ss");
String dateString = formatter.format(new Date(System
.currentTimeMillis()));
return (file.getAbsolutePath() + "/" + "Rec_" + dateString + file_exts[currentFormat]);
}
}
and broadcast receiver is this:--
public class MyPhoneReceiver extends BroadcastReceiver {
private String phoneNumber;
#Override
public void onReceive(Context context, Intent intent) {
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String extraState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(Constants.TAG, "MyPhoneReciever phoneNumber "+phoneNumber);
if (MainActivity.updateExternalStorageState() == Constants.MEDIA_MOUNTED) {
try {
SharedPreferences settings = context.getSharedPreferences(
Constants.LISTEN_ENABLED, 0);
boolean silent = settings.getBoolean("silentMode", true);
if (extraState != null) {
if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Intent myIntent = new Intent(context,
RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_CALL_START);
context.startService(myIntent);
} else if (extraState
.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Intent myIntent = new Intent(context,
RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_CALL_END);
context.startService(myIntent);
} else if (extraState
.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
if (phoneNumber == null)
phoneNumber = intent
.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent myIntent = new Intent(context,
RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_INCOMING_NUMBER);
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("silentMode", silent);
context.startService(myIntent);
}
} else if (phoneNumber != null) {
Intent myIntent = new Intent(context, RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_INCOMING_NUMBER);
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("silentMode", silent);
context.startService(myIntent);
}
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
}
}
}
}

Related

Record call in seperate files when call put on hold or end current call and pick new call at time

I have been working on app that record calls in background. In my onReceive method i am trying to record incoming and outgoing call by using TelephonyManager and that works fine. but, Now I want to record calls in Seperate files when first call is running or answered and another call came and put first call on hold or something. I dont' know how to do that.
Somehow, this code record call only in one file.
Here is my Recording class
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String 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.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(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();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String 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.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
Please, any help?

application integration with google drive

I am working with android application integration with google drive.I want to upload .csv file of backup to google drive..But error found. my code is here..there is error after choose picture from gallery that : com.google.api.client.googleapis.extentions.android.gms.auth.GoogleAuthIOException
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Connect to Google Drive
mCredential = GoogleAccountCredential.usingAudience(MainActivity.this,"852032254538-54h2nh1h5f2c4bg7ubash64d4vtcsc4f.apps.googleusercontent.com");
startActivityForResult(mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
mContext = MainActivity.this;
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView1);
OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
downloadItemFromList(position);
}
};
mListView.setOnItemClickListener(mMessageClickedHandler);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_STORE_FILE);
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService
.files();
Files.List request = null;
do {
try {
request = f1.list();
request.setQ("trashed=false");
FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
request.setPageToken(fileList
.getNextPageToken());
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(),
REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
if (request != null) {
request.setPageToken(null);
}
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
populateListView();
}
});
t.start();
}
});
}
private void downloadItemFromList(int position) {
mDLVal = (String) mListView.getItemAtPosition(position);
showToast("You just pressed: " + mDLVal);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for (File tmp : mResultList) {
if (tmp.getTitle().equalsIgnoreCase(mDLVal)) {
if (tmp.getDownloadUrl() != null
&& tmp.getDownloadUrl().length() > 0) {
try {
com.google.api.client.http.HttpResponse resp = mService
.getRequestFactory()
.buildGetRequest(
new GenericUrl(tmp
.getDownloadUrl()))
.execute();
InputStream iStream = resp.getContent();
try {
final java.io.File file = new java.io.File(
Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)
.getPath(), tmp.getTitle());
showToast("Downloading: "
+ tmp.getTitle()
+ " to "
+ Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)
.getPath());
storeFile(file, iStream);
} finally {
iStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
});
t.start();
}
private void populateListView() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mFileArray = new String[mResultList.size()];
int i = 0;
for (File tmp : mResultList) {
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
}
});
}
private void storeFile(java.io.File file, InputStream iStream) {
try {
final OutputStream oStream = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = iStream.read(buffer)) != -1) {
oStream.write(buffer, 0, read);
}
oStream.flush();
} finally {
oStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null
&& data.getExtras() != null) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
mService = getDriveService(mCredential);
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
// account already picked
} else {
startActivityForResult(mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
break;
case RESULT_STORE_FILE:
mFileUri = data.getData();
// Save the file to Google Drive
saveFileToDrive();
break;
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// Create URI from real path
String path;
path = getPathFromUri(mFileUri);
mFileUri = Uri.fromFile(new java.io.File(path));
ContentResolver cR = MainActivity.this.getContentResolver();
Log.d("tag123", "go to save in drive");
// File's binary content
java.io.File fileContent = new java.io.File(mFileUri
.getPath());
Log.d("tag123", "get path from resourse");
FileContent mediaContent = new FileContent(cR
.getType(mFileUri), fileContent);
Log.d("tag123", "selected");
showToast("Selected " + mFileUri.getPath() + "to upload");
// File's meta data.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType(cR.getType(mFileUri));
Log.d("tag123", "store in other file");
com.google.api.services.drive.model.File file = mService
.files().insert(body, mediaContent).execute();
if (file != null) {
showToast("Uploaded: " + file.getTitle());
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
showToast("Transfer ERROR: " + e.toString());
}
}
});
t.start();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public String getPathFromUri(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Bug recording videos android

I'm trying to reocord many videos of 30 seconds in background but, after 20 or 30 videos my service wich is stoping and launching the process to record go slowly.
I have try with a service in the same process and the problem was the same.
My video handler:
#Override
public void onCreate() {
super.onCreate();
isRunning = true;
idAlerta = Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "");
videoCount = 1;
mIntentRecorder = new Intent(VideoHandlerService.this, RecorderService.class);
mIntentSend = new Intent(VideoHandlerService.this, SendVideoService.class);
updateVideoTime();
mIntentRecorder.putExtra(Constants.VIDEO_TIME, videoTime);
mIntentRecorder.putExtra(Constants.ID_ALERTA_SERVICE, idAlerta);
mIntentRecorder.putExtra(Constants.COUNT_ALERTA, videoCount);
startService(mIntentRecorder);
newVideo();
}
public void newVideo() {
Common.log("new Video");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
videoCount++;
startNewVideo();
if (videoCount == 2)
sendVideo(4000);
}
}, videoTime + 2000);
}
public void startNewVideo() {
final Intent intentRecorder = new Intent(VideoHandlerService.this, RecorderService.class);
intentRecorder.putExtra(Constants.VIDEO_TIME, videoTime);
Common.log("idAlerta " + idAlerta);
intentRecorder.putExtra(Constants.ID_ALERTA_SERVICE, idAlerta);
intentRecorder.putExtra(Constants.COUNT_ALERTA, videoCount);
stopService(intentRecorder);
if (Common.getStorage().getBoolean(Constants.RECORDER_ACTIVE, false)) {
if (Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "") != null && Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "").length() > 0) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Common.log("Start service recorder");
startService(intentRecorder);
newVideo();
}
}, 5000);
}
} else
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startNewVideo();
}
}, 5000);
}
And this is the process to record:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Common.log("onStartCommand");
if (intent != null && ((Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "") != null && Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "").length() > 0))) {
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
//Cojo InformaciĆ³n del videohandler
Common.log("Intent distinto de null");
mVideoTime = intent.getIntExtra(Constants.VIDEO_TIME, 15000);
mIdAlerta = intent.getStringExtra(Constants.ID_ALERTA_SERVICE);
mVideoCount = intent.getIntExtra(Constants.COUNT_ALERTA, 1);
Common.log("Video time" + mVideoTime);
Common.getStorage().putBoolean(Constants.RECORDER_ACTIVE, true);
initRecording();
}
return START_NOT_STICKY;
}
public void initRecording() {
Common.log("INIT RECORDING IN");
surfaceView = new SurfaceView(this);
windowManager.addView(surfaceView, mLayoutParams);
surfaceView.getHolder().addCallback(this);
Common.log("INIT RECORDING OUT");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Common.log("onDestroy Video");
PreferenceHelper preferenceHelper = PreferenceHelper.newInstance(RecorderService.this, Constants.USER_PREFERENCES);
preferenceHelper.setBoolean(Constants.IS_RECORDING, false);
try {
camera.setPreviewCallback(null);
} catch (Exception e){
Common.log("error setPrevieCallback" + (e.getMessage() != null ? e.getMessage() : "sin mensaje"));
}
try {
muteSounds(false);
} catch (Exception e) {
Common.log(e.getMessage());
}
try {
Common.log("media recorder stop");
mediaRecorder.stop();
Common.log("media recorder reset");
mediaRecorder.reset();
Common.log("media recorder release");
mediaRecorder.release();
Common.log("media camera lock");
camera.lock();
Common.log("media camera release");
camera.release();
} catch (Exception e) {
}
Common.log("onDestroy Video");
Common.getStorage().putBoolean(Constants.RECORDER_ACTIVE, false);
RecorderService.super.onDestroy();
System.exit(0);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
Common.log("SurfaceCreated");
try {
try {
muteSounds(true);
} catch (Exception e) {
Common.log(e.getMessage());
}
Common.log("CAMERA OPEN 1");
try {
camera = Camera.open(1);
} catch (RuntimeException e) {
Common.log(e.getMessage());
}
Common.log("CAMERA OPEN 2");
///////////////////////////
mCamCoderProfile = CamcorderProfile.get(1, CamcorderProfile.QUALITY_LOW);
mCamCoderProfile.videoCodec = MediaRecorder.VideoEncoder.MPEG_4_SP;
mCamCoderProfile.audioCodec = MediaRecorder.AudioEncoder.AAC;
///////////////////////////
startRecorder();
} catch (Exception e) {
if (e.getMessage() != null)
Common.log(e.getMessage());
}
}
public void muteSounds(boolean mute) {
Common.log("MUTE SOUNDS IN");
AudioManager mgr = ((AudioManager) getSystemService(Context.AUDIO_SERVICE));
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (mute) {
mgr.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_MUTE, 0);
mgr.adjustVolume(AudioManager.ADJUST_MUTE, 0);
mgr.adjustVolume(AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE, 0);
} else {
mgr.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_UNMUTE, 0);
mgr.adjustVolume(AudioManager.ADJUST_UNMUTE, 0);
}
} else {
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, mute);
mgr.setStreamMute(AudioManager.STREAM_MUSIC, mute);
if (mute) {
mOlderVolumen = mgr.getStreamVolume(AudioManager.STREAM_RING);
mgr.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
} else
mgr.setStreamVolume(AudioManager.STREAM_RING, mOlderVolumen, 0);
mgr.adjustVolume(AudioManager.ADJUST_LOWER, 0);
}
Common.log("MUTE SOUNDS OUT");
}
public void startRecorder() {
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(mCamCoderProfile);
videoFile = new File(Environment.getExternalStorageDirectory() + "/" +
"wbunker_" + mIdAlerta + "_" + mVideoCount + ".mp4");
Common.log("Video rercorder name file " + videoRecording);
mediaRecorder.setOutputFile(videoFile.getPath());
mediaRecorder.setOrientationHint(270);
try {
Common.log("mediaRecorder prepare");
mediaRecorder.prepare();
Common.log("mediaRecorder prepare");
} catch (Exception e) {
}
Common.log("mediaRecorder start");
mediaRecorder.start();
Common.log("mediaRecorder start");
Common.log("Estoy grabando macho");
}
When I try to stop the service the services stops, but the camera isn't released even killing the app. Can someone help me?? thanks in advance.
In the onDestroy() method of your service replace the camera.lock() with camera.unLock() and in the startRecorder() method replace the camera.unLock() with camera.lock()
Finally the key was use PowerManager, if you are going to use it, don't forget to release it!
private fun lock() {
log("lock")
var powerManager: PowerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
powerWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "WakeLock-Manager")
powerWakeLock.acquire()
var wifiManger: WifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
wifiWakeLock = wifiManger.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "WifiLock-Manger")
wifiWakeLock.acquire()
log("lock")
}

implements service class the app is crash when phone switch off and on

I am new in android my question is that when i start the recording through power button with help of service class,code is proper work when i switch off my phone and open again, my app crash.Please help me..
My service class is:--
public class PowerButtonService extends Service implements MediaListner {
BroadcastReceiver mReceiver;
static final String AUDIO_RECORDER_FILE_EXT_MP3 = ".mp3";
static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private Handler mHandler;
SharedPreferences prefs;
private Runnable mRunnable;
String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP3,
AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private int count;
Sessions sessions;
int recordCount = 0;
private Editor mEditor;
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
MediaRecorder.OutputFormat.THREE_GPP };
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
sessions = new Sessions(PowerButtonService.this);
sessions.setServiceInstance(this);
prefs = getSharedPreferences("app", Context.MODE_PRIVATE);
mEditor = prefs.edit();
}
#Override
public void onDestroy() {
mEditor.putBoolean("PowerButtonServiceStart", false);
mEditor.commit();
unregisterReceiver(mReceiver);
Toast.makeText(getApplicationContext(),
"Recording from power button is stopped", Toast.LENGTH_SHORT)
.show();
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
final Vibrator vibe = (Vibrator) this
.getSystemService(Context.VIBRATOR_SERVICE);
if (!prefs.getBoolean("check", false)) {
recordCount = recordCount + 1;
if (recordCount == 3) {
if (prefs.getBoolean("RecordingOnInsideApp", false)) {
vibe.vibrate(1000);
recordCount = 0;
Toast.makeText(getApplicationContext(),
"Recording is already running", Toast.LENGTH_LONG)
.show();
} else {
mEditor.putBoolean("powerbutton", true);
mEditor.commit();
if (null == recorder && !(Sessions.getRecordOnActivity())) {
recordCount = 0;
System.out.println("recoding on");
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
vibe.vibrate(700);
Notifyuser();
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
if (null != recorder) {
mEditor.putBoolean("powerbutton", false);
mEditor.putString("PowerButtonTime",
"00:00:00");
count = 0;
mTimer.cancel();
mEditor.commit();
Sessions.setRecordOnService(false);
recordCount = 0;
recorder.stop();
recorder.reset();
recorder.release();
System.out.println("hello helloo");
Sessions.StopPowerButtonRecording();
vibe.vibrate(3000);
recorder = null;
}
Log.e("Ho rha hai", "goodndnd");
}
};
mHandler.postDelayed(mRunnable, 900000);
Sessions.setRecordOnService(true);
startTimer(mEditor);
Sessions.startPowerButtonServiceTime();
vibe.vibrate(1000);
} catch (Exception e) {
e.printStackTrace();
}
} else {
if ((Sessions.getRecordOnActivity())) {
Sessions.getServiceActivity();
vibe.vibrate(5000);
}
if (null != recorder) {
Sessions.setRecordOnService(false);
recordCount = 0;
recorder.stop();
recorder.reset();
recorder.release();
Sessions.stopServiceTimer();
vibe.vibrate(500);
recorder = null;
mEditor.putBoolean("powerbutton", false);
mEditor.putString("PowerButtonTime", "00:00:00");
count = 0;
mTimer.cancel();
mEditor.commit();
Sessions.setRecordOnService(false);
recordCount = 0;
recorder.stop();
recorder.reset();
recorder.release();
System.out.println("hello helloo");
Sessions.StopPowerButtonRecording();
vibe.vibrate(3000);
recorder = null;
}
}
}
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("time over...");
recordCount = 0;
}
}, 3000);
} else {
vibe.vibrate(1000);
Toast.makeText(getApplicationContext(),
"Recording from Widget is already Running",
Toast.LENGTH_LONG).show();
}
}
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd_MMM_yy_HH_mm_ss");
String dateString = formatter.format(new Date(System
.currentTimeMillis()));
return (file.getAbsolutePath() + "/" + "Rec_" + dateString + file_exts[currentFormat]);
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
}
};
private Timer mTimer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onMediaStopListner() {
if (null != recorder) {
if (mHandler != null) {
mHandler.removeCallbacks(mRunnable);
}
mEditor.putBoolean("powerbutton", false);
mEditor.putString("PowerButtonTime", "00:00:00");
count = 0;
if (mTimer != null) {
mTimer.cancel();
}
mEditor.commit();
recordCount = 0;
recorder.stop();
recorder.reset();
recorder.release();
Vibrator vibe = (Vibrator) this
.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(1000);
System.out.println("onMediaStopListner in Power button service");
System.out.println("powerbutton "
+ prefs.getBoolean("powerbutton", false));
System.out.println("PowerButtonTime "
+ prefs.getString("PowerButtonTime", ""));
recorder = null;
}
}
#Override
public void onMediaStartListner() {
}
#SuppressWarnings("deprecation")
public void Notifyuser() {
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, SplashActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.icon,
"Recording Start", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "Recording Find", ".....",
contentIntent);
notificationManager.notify(10, notification);
}
public void startTimer(final Editor editor) {
try {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
String timer = String.format("%02d:%02d:%02d",
count / 3600, (count % 3600) / 60, (count % 60));
count++;
editor.putString("PowerButtonTime", timer);
editor.commit();
System.out.println("This is only For Testing" + timer);
}
}, 1000, 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
if (prefs.getBoolean("powerbutton", false)) {
Toast.makeText(getApplicationContext(),
"Recording has been saved successfully", Toast.LENGTH_LONG)
.show();
final Vibrator vibe = (Vibrator) this
.getSystemService(Context.VIBRATOR_SERVICE);
if (null != recorder) {
mEditor.putBoolean("powerbutton", false);
mEditor.putString("PowerButtonTime", "00:00:00");
count = 0;
mTimer.cancel();
mEditor.commit();
Sessions.setRecordOnService(false);
recordCount = 0;
recorder.stop();
recorder.reset();
recorder.release();
System.out.println("hello helloo");
Sessions.StopPowerButtonRecording();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext()
.getSystemService(ns);
nMgr.cancel(10);
vibe.vibrate(3000);
recorder = null;
}
}
super.onTaskRemoved(rootIntent);
}

Android incoming call recording

I am trying to record the incoming voice call of the user.
My code is :
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String 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 String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String 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 String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("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;
}
#SuppressLint("InlinedApi")
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
#SuppressLint("InlinedApi")
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(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();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/RenzymTest123");
if (!sampleDir.exists())
{
try
{
sampleDir.mkdirs();
}
catch(Exception e)
{
Log.d("make directory",e.toString());
}
}
out = out.replace(" ", "");
out = out.replace("-", "");
String file_name = "Recordaa";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
//recorder.reset();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex)
{
ex.printStackTrace();
}
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.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
When I use this
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
I got exception while staring the recoder
Exception : java.lang.RuntimeException: start failed
I have searched on previosly asked asked questions but didnt find any solution
on link Android Media Recording: java.lang.RuntimeException: start failed
it says to use
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); instead of voice call but records outing voice not incoming voice. How can I record incoming voice
An audio source of MIC should record incoming calls. You can set recording volume to the maximum level and turn on loudspeaker too as follows:
//before recording
AudioManager audioManager;
//turn on speaker
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
//increase Volume
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
//start recording
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setAudioEncodingBitRate(320000);
recorder.setAudioSamplingRate(44100);
File audioFile = File.createTempFile("temp", "3gp", path);
recorder.setOutputFile(audioFile.getAbsolutePath());
recorder.prepare();
recorder.start();
Also there are other constants you can use with setAudioSource(), Just follow the guide to understand how each works

Categories

Resources