I want to create small app MediaRecord on smsreciver. when i recive message recording start and stop autometically . My problem is on sms recive recording is start but its never stop on next sms recive and my recorded file is successfully created but there is nothing inside. plz help
public class BroadCast extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
private String recivedKey;
private MediaRecorder recorder;
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (messages.length > -1) {
if (messages[0].getOriginatingAddress() != null) {
if (recivedKey.equals(String.valueOf(record_key))) {
// Stop it being passed to the main Messaging
abortBroadcast();
startRecording();
SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendTextMessage(formattedNumber, null,
"Recording has been started, to stop recording any time send "
+ stop_record_key, null, null);
}
if (recivedKey.equals(String.valueOf(stop_record_key))) {
// Stop it being passed to the main Messaging
abortBroadcast();
stopRecording();
}
}
}
}
}
}
public void startRecording() {
System.out.println("STart Recording");
if (recorder != null) {
recorder.release();
} else {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
recorder.release();
}
}
}
private void stopRecording() {
System.out.println("Stop Recording");
try {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
private String getFilename() {
File rootsd = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
if (!rootsd.isDirectory()) {
rootsd.mkdir();
}
File dcim = new File(rootsd+"/"+System.currentTimeMillis()+".3gp");
return dcim.getAbsolutePath();
}
}
Related
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?
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();
}
}
}
}
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
i have an IntentService that receives messages from a server using GCM, everything is working fine except when i try to take a picture using android.hardware.Camera the InentService is destroyed before calling onPictureTaken ! , so what should i do to save captured photo before InentService stops ?
public class GcmIntentService extends IntentService {
String function;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
String msg = intent.getStringExtra("message");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
System.out.println("message received");
try {
json = new JSONObject(msg);
function = json.getString("function");
} catch (JSONException e) {
e.printStackTrace();
}
if (function.equals("capture")) {
System.out
.println("capture entereeeeed =====================");
Capture cap = new Capture(getApplicationContext());
cap.captureNow();
}
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
#Override
public void onDestroy() {
if (Capture.camera != null) {
System.out.println("camera released");
Capture.camera.release();
}
super.onDestroy();
}
}
the Capture Class , from the vogella tutorial http://www.vogella.com/tutorials/AndroidCamera/article.html
public class Capture {
Context captureContext = null;
public static Camera camera;
private int cameraId = 0;
final static String DEBUG_TAG = "Capture Class";
public Capture(Context context) {
captureContext = context;
// do we have a camera?
if (!captureContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
System.out.println("no camera found on this device");
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
System.out.println("no front camera found");
} else {
camera = Camera.open(cameraId);
}
}
}
public void captureNow() {
System.out.println("capture now entered");
camera.takePicture(null, null, new PhotoHandler(captureContext));
}
public int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
}
the PhotoHandler Class
public class PhotoHandler implements PictureCallback {
private final Context context;
public static String filename;
public PhotoHandler(Context context) {
System.out.println("enetered photoHandler");
this.context = context;
}
#Override
public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
System.out.println("entered onPicture taken");
File pictureFileDir = getDir();
System.out.println("file directory = " + pictureFileDir);
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d(Capture.DEBUG_TAG, "Can't create directory to save image.");
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
System.out.println("New Image saved: " + photoFile);
Capture.camera.release();
} catch (Exception error) {
Log.d(Capture.DEBUG_TAG,
"File" + filename + "not saved: " + error.getMessage());
System.out.println("image could not be saved");
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "blah");
}
}
Answer is simple Just do the Camera stuff in an AsyncTask. Probably will work.
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
String msg = intent.getStringExtra("message");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
System.out.println("message received");
try {
json = new JSONObject(msg);
function = json.getString("function");
} catch (JSONException e) {
e.printStackTrace();
}
if (function.equals("capture")) {
System.out.println("capture entereeeeed =====================");
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void...params) {
Capture cap = new Capture(getApplicationContext());
cap.captureNow();
String result = "ok";
return result;
}
#Override
protected void onPostExecute(String result) {
}
}.execute();
}
}
}
is there anyway I can send an email when I press the save button with OUTPUT_FILE path from sdcard. (I didn't implement the save button yet)
Should I change String to Uri instead to send an email?
I don't know how I should implement the save button making it to send an email with the audio file attached. Any suggestions? Thanks in advance!
public class FulfillAudioTaskActivity extends Activity {
private MediaPlayer mediaPlayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fulfill_audio_task);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/audiorecorder.3gpp";
}
public void buttonTapped(View view){
switch(view.getId()) {
case R.id.startBtn:
try {
beginRecording();
}catch (Exception e){
e.printStackTrace();
}
break;
case R.id.finishBtn:
try {
stopRecording();
} catch (Exception e){
e.printStackTrace();
}
break;
case R.id.playBtn:
try {
playRecording();
} catch (Exception e){
e.printStackTrace();
}
break;
case R.id.stopBtn:
try {
stopPlayback();
} catch (Exception e){
e.printStackTrace();
}
break;
}
}
private void stopPlayback() {
if(mediaPlayer != null)
mediaPlayer.stop();
}
private void playRecording() throws Exception{
ditchMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void ditchMediaPlayer() {
if(mediaPlayer != null)
{
try {
mediaPlayer.release();
}catch(Exception e){
e.printStackTrace();
}
}
}
// stop recording if there's a recorder running
private void stopRecording() {
if (recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception {
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//check if there's a file already recorded, and if it is we want to get rid of it.
if(outFile.exists())
outFile.delete();
//create a new MediaRecorder object.
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
recorder.setOutputFile(OUTPUT_FILE);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
// TODO Auto-generated method stub
if(recorder != null)
recorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_fulfill_audio_task, menu);
return true;
}
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("audio/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {"someone#gmail.com"} );
i.putExtra(Intent.EXTRA_SUBJECT, "MySubject");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "audiorecorder.3gpp");
startActivity(i);
Hope this helps!