I am trying to create a class that sets and starts audio recording but as soon as I click the button the app crashes. Iv isolated the problem to where I set the parameters for the MediRecorder.
private void startRec() throws IOException {
if (mrecorder!=null)
mrecorder.release();
mrecorder= new MediaRecorder();
-> mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
/*
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrecorder.setOutputFile(MFILE);
mrecorder.prepare();
mrecorder.start();
*/
}
It crashes when the line with the arrow above the start of the notes is executed. I added the following permission to the manifest as well:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Any help much appreciated.
UPDATED LOGCAT
[ 05-12 00:39:13.299 30086:30158 D/ ]
ro.exynos.dss isEnabled: 0
05-12 00:39:13.309 30086-30158/record66.record6 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
05-12 00:39:13.319 30086-30086/record66.record6 W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
05-12 00:39:13.319 30086-30158/record66.record6 D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : record66.record6
05-12 00:39:13.359 30086-30086/record66.record6 D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
05-12 00:39:13.389 30086-30086/record66.record6 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#682466c time:234401322
05-12 00:39:15.749 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 0
05-12 00:39:15.879 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 1
05-12 00:39:15.929 30086-30086/record66.record6 D/AndroidRuntime: Shutting down VM
05-12 00:39:15.939 30086-30086/record66.record6 E/AndroidRuntime: FATAL EXCEPTION: main
Process: record66.record6, PID: 30086
java.lang.RuntimeException: setAudioSource failed.
at android.media.MediaRecorder._setAudioSource(Native Method)
at android.media.MediaRecorder.setAudioSource(MediaRecorder.java:488)
at record66.record6.MainActivity.startRec(MainActivity.java:58)
at record66.record6.MainActivity.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
05-12 00:39:17.909 30086-30086/record66.record6 I/Process: Sending signal. PID: 30086 SIG: 9
Please see what logcat is.
And let us know what error you are getting. So can help.
package com.example.dhrupalpatel.test;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity implements View.OnClickListener{
MediaRecorder mrecorder;
boolean mStartRecording=false;
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start =(Button)findViewById(R.id.start);
stop =(Button)findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
private void startRec() throws IOException {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
File sdCardDirectory= Environment
.getExternalStorageDirectory();
if(mExternalStorageAvailable && !sdCardDirectory.exists())
{
sdCardDirectory.mkdir();
}
File f= new File(sdCardDirectory.getPath()+"/"+System.currentTimeMillis()+".mp3");
if( mrecorder == null ) {
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setOutputFile(f.getPath());
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if(!mStartRecording) {
try {
mrecorder.prepare();
mrecorder.start();
mStartRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRec() throws IOException {
if(mStartRecording) {
mStartRecording = false;
mrecorder.stop();
mrecorder.reset();
mrecorder.release();
mrecorder = null;
}
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.start:
try {
startRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stop:
try {
stopRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Related
I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
I'm am trying to capture an image in the ontouchevent of surfaceview. However, everytime a touch the screen, the app crashes with the following exception:
01-05 21:03:18.500: ERROR/AndroidRuntime(10367): FATAL EXCEPTION: main
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1126)
at android.hardware.Camera.takePicture(Camera.java:1071)
at com.test.MotionDetector.CameraSurfaceView.onTouchEvent(CameraSurfaceView.java:107)
at android.view.View.dispatchTouchEvent(View.java:7350)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2470)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2212)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2470)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2212)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2470)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2212)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2151)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1480)
at android.app.Activity.dispatchTouchEvent(Activity.java:2469)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2099)
at android.view.View.dispatchPointerEvent(View.java:7535)
at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3492)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3424)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4534)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4512)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4616)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:125)
at android.os.Looper.loop(Looper.java:124)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
My code:
package com.nadim.MotionDetector;
import android.content.Context;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private Context context;
public CameraSurfaceView(Context context, Camera camera) {
super(context);
this.context = context;
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("MotionDetector", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d("MotionDetector", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(context, "Picture taken", Toast.LENGTH_SHORT).show();
//System.gc(); tried this because it was suggested in a stackoverflow question but it didn't help.
mCamera.takePicture(null, mPicture, mPicture);
return true; //processed
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("MotionDetector", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("MotionDetector", "Error accessing file: " + e.getMessage());
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "motiondetect");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir, timeStamp + ".jpg");
return mediaFile;
}
}
Permissions and features used:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />
I don't know why the crash occurs. Many other topic suggest calling Camera.startPreview first. I am doing that, but it doesn't solve the issue.
LogCat before taking picture:
01-05 21:45:57.667: WARN/ActivityManager(754): No content provider found for permission revoke: file:///data/local/tmp/com.test.MotionDetector
01-05 21:45:57.667: WARN/ActivityManager(754): No content provider found for permission revoke: file:///data/local/tmp/com.test.MotionDetector
01-05 21:45:57.687: INFO/ActivityManager(754): Force stopping com.test.MotionDetector appid=10103 user=-1: uninstall pkg
01-05 21:45:57.687: INFO/ActivityManager(754): Killing 4264:com.test.MotionDetector/u0a103 (adj 7): stop com.test.MotionDetector
01-05 21:45:57.687: INFO/ActivityManager(754): Force finishing activity ActivityRecord{437a6678 u0 com.test.MotionDetector/.MotionDetectActivity t144}
01-05 21:45:57.697: WARN/InputDispatcher(754): channel '42adff40 com.test.MotionDetector/com.test.MotionDetector.MotionDetectActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
01-05 21:45:57.697: ERROR/InputDispatcher(754): channel '42adff40 com.test.MotionDetector/com.test.MotionDetector.MotionDetectActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-05 21:45:57.697: WARN/InputDispatcher(754): Attempted to unregister already unregistered input channel '42adff40 com.test.MotionDetector/com.test.MotionDetector.MotionDetectActivity (server)'
01-05 21:45:57.697: INFO/WindowState(754): WIN DEATH: Window{42adff40 u0 com.test.MotionDetector/com.test.MotionDetector.MotionDetectActivity}
01-05 21:45:57.757: INFO/PackageManager(754): Running dexopt on: com.test.MotionDetector
01-05 21:45:57.757: INFO/PackageManager(754): Package com.test.MotionDetector codePath changed from /data/app/com.test.MotionDetector-1.apk to /data/app/com.test.MotionDetector-2.apk; Retaining data and using new
01-05 21:45:57.807: INFO/ActivityManager(754): Force stopping com.test.MotionDetector appid=10103 user=-1: update pkg
01-05 21:45:57.807: WARN/PackageManager(754): Code path for pkg : com.test.MotionDetector changing from /data/app/com.test.MotionDetector-1.apk to /data/app/com.test.MotionDetector-2.apk
01-05 21:45:57.807: WARN/PackageManager(754): Resource path for pkg : com.test.MotionDetector changing from /data/app/com.test.MotionDetector-1.apk to /data/app/com.test.MotionDetector-2.apk
01-05 21:45:57.937: INFO/ActivityManager(754): Force stopping com.test.MotionDetector appid=10103 user=0: pkg removed
01-05 21:45:57.987: DEBUG/BackupManagerService(754): Received broadcast Intent { act=android.intent.action.PACKAGE_REMOVED dat=package:com.test.MotionDetector flg=0x4000010 (has extras) }
01-05 21:45:58.047: DEBUG/BackupManagerService(754): Received broadcast Intent { act=android.intent.action.PACKAGE_ADDED dat=package:com.test.MotionDetector flg=0x4000010 (has extras) }
01-05 21:45:58.567: INFO/Icing.InternalIcingCorporaProvider(12750): Updating corpora: A: com.test.MotionDetector, C: MAYBE
01-05 21:45:58.647: DEBUG/PackageAddedReceiver(1086): package added com.test.MotionDetector
01-05 21:45:58.737: INFO/ActivityManager(754): START u0 {flg=0x10000000 cmp=com.test.MotionDetector/.MotionDetectActivity} from pid 4578
01-05 21:45:58.777: INFO/ActivityManager(754): Start proc com.test.MotionDetector for activity com.test.MotionDetector/.MotionDetectActivity: pid=4630 uid=10103 gids={50103, 1028, 1015}
01-05 21:45:59.627: INFO/ActivityManager(754): Displayed com.test.MotionDetector/.MotionDetectActivity: +861ms (total +972ms)
01-05 21:45:59.657: INFO/WindowManager(754): Screen frozen for +869ms due to Window{43cb77a8 u0 com.test.MotionDetector/com.test.MotionDetector.MotionDetectActivity}
Assuming that you want the jpeg saved, you don't need raw callback, so
change the call to takePicture() from:
mCamera.takePicture(null, mPicture, mPicture);
to
mCamera.takePicture(null, null, mPicture);
in your onTouchEvent(). This will use jpeg picture callback.
Calling takePicture() also causes the preview to stop, so you might want to call startPreview() again in your onPictureTaken() callback, if you want to take more pictures or have a preview restarted.
Also, in your onTouchEvent(), you might be getting multiple events, so filter for the one that works for you:
#Override
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(context, "Picture taken", Toast.LENGTH_SHORT).show();
//System.gc(); tried this because it was suggested in a stackoverflow question but it didn't help.
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// A pressed gesture has started, the motion contains the initial starting location
break;
case MotionEvent.ACTION_UP:
// A pressed gesture has finished, the motion contains the final release location
// as well as any intermediate points since the last down or move event.
mCamera.takePicture(null, mPicture, mPicture);
break;
default:
break;
}
return true; //processed
}
If you place takePicture() in ACTION_DOWN, it will be called as soon as you touch the screen, whereas when in ACTION_UP, it will happen when you remove finger. See which one works for you.
I am trying to switch activities in android using intent. However no matter what I do, this always crashes. I read countless topics on the same question, none of which have helped. So I Am Forced to ask my own question.
When I Run This, the app simply crashes after the 4 seconds are up
Here Is My First Activity (Splash):
package com.redflamedeveloper.torch;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
/** Called when the activity is first created. */
MediaPlayer mpSplash;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mpSplash = MediaPlayer.create(this, R.raw.fire); //Splash Screen sound
mpSplash.start();
Thread logoTimer = new Thread(){ //4 Second Timer
public void run() {
try {
//Waits for 4 seconds
int logoTimer = 0;
while(logoTimer <4000){
sleep(100);
logoTimer = logoTimer + 100;
}
Intent intentMain = new Intent(Splash.this, Main.class);
startActivity(intentMain);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
finish();
}
}
};
logoTimer.start(); //Starts the thread logoTimer
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mpSplash.release(); //ends sound
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mpSplash.pause(); //pauses sound
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mpSplash.start(); //Resumes sound
}
}
My Second Activity (Main):
package com.redflamedeveloper.torch;
import android.app.Activity;
import android.hardware.Camera.Parameters;
import android.hardware.Camera;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Handler;
/**
* Created by Sasha on 8/12/13.
*/
public class Main extends Activity implements OnClickListener{
private Camera mCamera;
boolean torch = false;
boolean flash = false;
private Handler mHander = new Handler();
private final Runnable mRunnable = new Runnable() {
public void run() {
while(flash) {
if (torch==false) {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
torch=true;
}
} else {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
torch=false;
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
Button bTorch = (Button) findViewById(R.id.bTorch);
Button bFlash = (Button) findViewById(R.id.bFlash);
Button bHelp = (Button) findViewById(R.id.bHelp);
Button bMorse = (Button) findViewById(R.id.bMorse);
bTorch.setOnClickListener(this);
bFlash.setOnClickListener(this);
bHelp.setOnClickListener(this);
bMorse.setOnClickListener(this);
}
private void startStrobe() {
mHander.post(mRunnable);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bTorch:
if (torch==false) {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
torch=true;
}
} else {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
torch=false;
}
}
break;
case R.id.bFlash:
flash=!flash;
startStrobe();
break;
case R.id.bHelp:
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case R.id.bMorse:
Intent intentMorse = new Intent(Main.this, Morse.class);
Main.this.startActivity(intentMorse);
break;
}
}
}
And My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redflamedeveloper.torch"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.redflamedeveloper.torch.Splash"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Morse"
android:label="#string/app_name" >
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
</manifest>
And Finally LogCat:
12-09 23:28:35.682 2110-2110/com.redflamedeveloper.torch W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40c47a68)
12-09 23:28:35.692 637-674/? E/android.os.Debug﹕ !#Dumpstate > dumpstate -k -t -n -z -d -o /data/log/dumpstate_app_error
12-09 23:28:35.692 2110-2110/com.redflamedeveloper.torch E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.app.SuperNotCalledException: Activity {com.redflamedeveloper.torch/com.redflamedeveloper.torch.Main} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1936)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
12-09 23:28:35.692 637-647/? W/ActivityManager﹕ Force finishing activity com.redflamedeveloper.torch/.Main
12-09 23:28:35.702 2144-2144/? I/dumpstate﹕ Check if stand-alone
12-09 23:28:35.712 2144-2144/? I/dumpstate﹕ begin
12-09 23:28:36.523 1268-1281/? E/MP-Decision﹕ DOWN Ld:54 Ns:1.100000 Ts:190 rq:0.000000 seq:196.000000
12-09 23:28:37.023 637-25450/? W/SignalStrength﹕ getGsmLevel=4
12-09 23:28:37.023 637-25450/? W/SignalStrength﹕ getLevel=4 (SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4)
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getGsmLevel=4
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getLevel=4 (SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4)
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getGsmLevel=4
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getLevel=4 (SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4)
12-09 23:28:37.023 771-771/? D/STATUSBAR-NetworkController﹕ onSignalStrengthsChanged signalStrength=SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4 level=4
12-09 23:28:37.023 637-884/? W/AlarmManager﹕ FACTORY_ON= 0
12-09 23:28:37.774 1268-1281/? E/MP-Decision﹕ UP Ld:61 Nw:1.990000 Tw:140 rq:2.300000 seq:147.000000
12-09 23:28:38.164 329-329/? E/SMD﹕ DCD ON
12-09 23:28:38.665 336-582/? D/AudioStreamOutALSA﹕ standby
12-09 23:28:38.665 336-582/? D/ALSAModule﹕ s_standby: handle 0x10454c0 h 0x0
12-09 23:28:38.665 336-582/? E/ALSAModule﹕ s_standby handle h 0x10e2180
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ snd_use_case_set(): uc_mgr 0xfe8968 identifier _verb value Inactive
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ set_use_case_ident_for_all_devices(): HiFi
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ Set mixer controls for HiFi enable 0
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ Set mixer controls for HiFiSpeaker enable 0
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ snd_use_case_set(): uc_mgr 0xfe8968 identifier _disdev value Main Mic
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ disdev: device Main Mic not enabled or not active, no need to disable
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ snd_use_case_set(): uc_mgr 0xfe8968 identifier _disdev value Speaker
12-09 23:28:38.865 336-582/? E/alsa_ucm﹕ Empty list
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ set current output is none
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ Set mixer controls for Speaker enable 0
12-09 23:28:39.075 1268-1281/? E/MP-Decision﹕ DOWN Ld:18 Ns:1.100000 Ts:190 rq:0.000000 seq:196.000000
12-09 23:28:40.557 319-542/? D/VoldCmdListener﹕ asec list
12-09 23:28:40.557 319-542/? D/VoldCmdListener﹕ CommandListener::AsecCmd::runCommand -> --
12-09 23:28:40.707 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.707 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.707 637-698/? D/DEFERED_APP_VISIBILITY﹕ tweaking closing app
12-09 23:28:40.707 637-698/? D/DEFERED_APP_VISIBILITY﹕ tweaking closing app
12-09 23:28:40.717 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.737 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.747 637-698/? D/KeyguardViewMediator﹕ setHidden false
I am At my wits end. All help will be greatly appreciated
Sasha
You need to call super.onCreate(savedInstanceState); in the onCreate method of Main.class
Your second activity does not call super.onCreate(savedInstanceState). It says so in the logcat
Im trying to save an Audio record from the Microphone, to a File Object, instead of a File. Why? Because i only need to save the record, while the App is active. This is what i tried, using the "Audio Capture" tutorial from developer.android.com
private Button b1;
private Button b2;
private ProgressBar bar;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private boolean recording = false;
private boolean playing = false;
public AudioRecordDialog(Context context, final MainActivity main) {
super(context);
setTitle(R.string.setupSound);
setContentView(R.layout.audio_record_dialog_layout);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setAlpha(0);
b1 = (Button) findViewById(R.id.button1);
b1.setText(R.string.startButton);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recording) {
b1.setText(R.string.startButton);
recording = false;
bar.setAlpha(0);
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
mRecorder = null;
} else {
b1.setText(R.string.stopButton);
recording = true;
bar.setAlpha(1);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("record.3gp");
try {
mRecorder.prepare();
} catch (IOException e) {
Toast toast = Toast.makeText(getContext(),
"Failed Recording!", Toast.LENGTH_SHORT);
toast.show();
}
mRecorder.start();
}
}
});
b2 = (Button) findViewById(R.id.button2);
b2.setText(R.string.playButton);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (playing) {
b2.setText(R.string.playButton);
playing = false;
if (mPlayer != null)
mPlayer.release();
mPlayer = null;
} else {
b2.setText(R.string.pauseButton);
playing = true;
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource("record.3gp");
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Toast toast = Toast.makeText(getContext(),
"Failed Playing soundFile!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
});
But it doesnt work and crashes upon clicking the record-Button.
Here is the logCat.
08-28 02:07:14.144: E/Trace(17588): error opening trace file: Permission denied (13)
08-28 02:07:14.324: D/SensorManager(17588): caller of registerListener:17588,sensor type:3
08-28 02:07:14.410: D/libEGL(17588): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
08-28 02:07:14.425: D/libEGL(17588): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
08-28 02:07:14.425: D/libEGL(17588): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
08-28 02:07:14.511: D/OpenGLRenderer(17588): Enabling debug mode 0
08-28 02:07:17.785: E/MediaRecorder(17588): start called in an invalid state: 4
08-28 02:07:17.785: D/AndroidRuntime(17588): Shutting down VM
08-28 02:07:17.785: W/dalvikvm(17588): threadid=1: thread exiting with uncaught exception (group=0x40ddd2a0)
08-28 02:07:17.793: E/AndroidRuntime(17588): FATAL EXCEPTION: main
08-28 02:07:17.793: E/AndroidRuntime(17588): java.lang.IllegalStateException
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.media.MediaRecorder.start(Native Method)
08-28 02:07:17.793: E/AndroidRuntime(17588): at com.notfall.notruf.AudioRecordDialog$1.onClick(AudioRecordDialog.java:74)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.view.View.performClick(View.java:4106)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.view.View$PerformClick.run(View.java:17052)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.os.Handler.handleCallback(Handler.java:615)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.os.Handler.dispatchMessage(Handler.java:92)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.os.Looper.loop(Looper.java:137)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.app.ActivityThread.main(ActivityThread.java:5118)
08-28 02:07:17.793: E/AndroidRuntime(17588): at java.lang.reflect.Method.invokeNative(Native Method)
08-28 02:07:17.793: E/AndroidRuntime(17588): at java.lang.reflect.Method.invoke(Method.java:511)
08-28 02:07:17.793: E/AndroidRuntime(17588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
08-28 02:07:17.793: E/AndroidRuntime(17588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
08-28 02:07:17.793: E/AndroidRuntime(17588): at dalvik.system.NativeStart.main(Native Method)
08-28 02:07:19.191: I/Process(17588): Sending signal. PID: 17588 SIG: 9
it crashes on
mRecorder.start();
You should call setAudioEncoder() after setOutputFormat().
I try #Tarsem answer already but have fatal error occur can I know why?
#Tarsem answer:
https://stackoverflow.com/a/18308611/2398886
<--- these are my error codes in eclipse: --->
08-21 18:52:23.399: W/dalvikvm(29376): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-21 18:52:23.409: E/AndroidRuntime(29376): FATAL EXCEPTION: main
08-21 18:52:23.409: E/AndroidRuntime(29376): java.lang.NoClassDefFoundError: com.example.testing01.MainActivity2$6
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2.CaptureMapScreen(MainActivity2.java:410)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2$3.onClick(MainActivity2.java:182)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View.performClick(View.java:2485)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View$PerformClick.run(View.java:9080)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.handleCallback(Handler.java:587)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Looper.loop(Looper.java:130)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invoke(Method.java:507)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:867)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-21 18:52:23.409: E/AndroidRuntime(29376): at dalvik.system.NativeStart.main(Native Method)
<--- these are my error codes in eclipse: --->
and these are my coding, is it my coding any bug?
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
my Stop Button function:
//End Button Function
Button timerStopButton = (Button) findViewById(R.id.btnTimerStop);
timerStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String latitude3=Double.toString(latitude1);
String latitude4=Double.toString(latitude2);
String longitude3=Double.toString(longitude1);
String longitude4=Double.toString(longitude2);
String Kcalories=String.format("%.2f", calories);
Intent intent = new Intent(view.getContext(),NewDataActivity.class);
intent.putExtra("lat1", latitude3);
intent.putExtra("lat2", latitude4);
intent.putExtra("long1", longitude3);
intent.putExtra("long2", longitude4);
intent.putExtra("timer", timerStop1);
intent.putExtra("distance", distance2 + " m");
intent.putExtra("Ccalories", Kcalories + " kcal");
Toast.makeText(getApplicationContext(), "Calories (kcal):" + Kcalories, Toast.LENGTH_LONG).show();
startActivity(intent);
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//kill task timer and other
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
});
Is it my coding have any bug or my logic any probelm?
can anyone help me? thanks :)
Note Your code to Capture Map Screen is Correct and if still you have confusion than
Please Make sure Each Step Below:-
Below are the steps to capture screen shot of Google Map V2 with example
Step 1. open Android Sdk Manager (Window > Android Sdk Manager) then Expand Extras now update/install Google Play Services to Revision 10 ignore this step if already installed
Read Notes here https://developers.google.com/maps/documentation/android/releases#august_2013
Step 2. Restart Eclipse
Step 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
Step 4. Make Method to Capture/Store Screen/image of Map like below
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
myMap.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
Step 5. Now call this CaptureMapScreen() method where you want to capture the image
in my case i am calling this method on Button click in my onCreate() which is working fine
like:
Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
btnCap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Check Doc here and here