Following code uses to get jpeg-photo from camera
public void getPhoto(final PictureCallback callback, final Runnable focusFailCallback) {
if(!Camera.Parameters.FOCUS_MODE_FIXED.equals(mCamera.getParameters().getFocusMode()) &&
!Camera.Parameters.FOCUS_MODE_INFINITY.equals(mCamera.getParameters().getFocusMode())) {
mCamera.autoFocus(new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
if(success) {
camera.takePicture(null, null, null, callback);
} else {
camera.cancelAutoFocus();
focusFailCallback.run();
}
}
});
} else {
mCamera.takePicture(null, null, null, callback);
}
}
Mostly it works fine. It calls between startPreview and stopPreview calls, so I have not problems about that. But at random moments it can throw exception.
java.lang.RuntimeException: takePicture failed
android.hardware.Camera.native_takePicture(Native Method)
android.hardware.Camera.takePicture(Camera.java:1828)
org.opencv.android.JavaCameraView$2.onAutoFocus(JavaCameraView.java:463)
android.hardware.Camera$EventHandler.handleMessage(Camera.java:1273)
android.os.Handler.dispatchMessage(Handler.java:111)
android.os.Looper.loop(Looper.java:194)
android.app.ActivityThread.main(ActivityThread.java:5534)
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke(Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
I have no idea what could happen that I didn't provide for.
I had the same issue on a Moto E3 and some other devices and calling cancelAutoFocus right before camera.takePicture made the crash disappear.
Related
Im writing my project app in Android Studio. The app is connected to microcontroller and send logic 1 on button Click to get data string from microcontroller all by BT. I have question for you how can i automatize it to send this logic 1 with some delay. I tried some methods but them dont work properly. The app stops
//Send Button
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendButton.performClick();
}
},20000);
LogCat:
2020-03-27 18:44:10.913 11754-11754/com.example.bt_serial_test_1_0 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bt_serial_test_1_0, PID: 11754
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:5645)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5640)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Caused by: java.lang.IllegalArgumentException: Invalid message body
at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:337)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:325)
at com.example.bt_serial_test_1_0.MainActivity.sendSms(MainActivity.java:239)
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5640)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
this method is in onCreate. Can someone please help me to resolve this problem
Here is a Handler example for a repeating task.
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
You can modify it for your case like that
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
handler().postDelayed(r,1000);
}
catch (IOException ex) { }
}
});
final Runnable r = new Runnable()
{
public void run()
{
sendButton.performClick();
}
};
I am getting this error in my published application, only clients receive this error. I already tried several times to replicate the same mistake however unsuccessfully.
I also already tried to use the below code at all locations where there is a Dialog but also not solved.
if (dialog.isShowing ()) {
dialog.dismiss ();
}
The error report
java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{16faa139 V.E..... R.....I. 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:412)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:338)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:122)
at android.app.Dialog.dismissDialog(Dialog.java:522)
at android.app.Dialog.dismiss(Dialog.java:504)
**at br.my.project.de.a(Unknown Source)
at br.my.project.de.onPostExecute(Unknown Source)**
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
I could see that you are trying to dismiss a ProgressDialog on the postExecute of an AsyncTask. This in itself is a good practice but is sometimes buggy, I kind of experienced this also before especially while you're showing the ProgressDialog and suddenly rotate the view.
A solution I've found to fix this is below:
You will need these function to handle the proper dismissal and avoid crashes.
private void dismissProgressDialog(ProgressDialog progressDialog) {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
//get the Context object that was used to create the dialog
Context context = ((ContextWrapper) progressDialog.getContext()).getBaseContext();
// if the Context used here was an activity AND it hasn't been finished or destroyed
// then dismiss it
if (context instanceof Activity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
dismissWithExceptionHandling(progressDialog);
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!((Activity) context).isFinishing()) {
dismissWithExceptionHandling(progressDialog);
}
}
} else
// if the Context used wasn't an Activity, then dismiss it too
dismissWithExceptionHandling(progressDialog);
}
progressDialog = null;
}
}
public void dismissWithExceptionHandling(ProgressDialog dialog) {
try {
dialog.dismiss();
} catch (final IllegalArgumentException e) {
// Do nothing.
} catch (final Exception e) {
// Do nothing.
} finally {
dialog = null;
}
}
On your AsyncTask's onPostExecute implement the function.
#Override
protected void onPostExecute(Boolean b) {
// pass in the progressDialog as a parameter to the method
dismissProgressDialog(progressDialog);
}
fun Activity?.dismissDialog(dialog: Dialog?) {
if (isActivityActive()) {
dialog?.apply {
if (isShowing) dismiss()
}
}
}
fun Activity?.isActivityActive(): Boolean {
return null != this && !isFinishing && !isDestroyed
}
You are calling dismiss on a dialog that is currently not being shown anymore. As in: your Activity/Fragment is possibly already destroyed when you call dismiss.
Write this code in your activity's
onStop()
method.When anybody presses the home button and if dialog is opened than this error will come. Because on click of home button onPause() and onStop() method calls.Hope this helps.
if (dialog!=null && dialog.isShowing ()) {
dialog.dismiss ();
}
I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
public class RegistrationActivity extends AppIntro {
private AsyncTaskRegisterInBackground registerPushToken;
(...)
#Override
public void onDonePressed() {
(...)
if (regid.isEmpty()) {
registerPushToken = new AsyncTaskRegisterInBackground();
registerPushToken.setParams(activity, gcm, regid);
registerPushToken.execute();
}
(...)
}
#Override
public void onTaskCompleted(String responseRegid) {
try {
// load authToken from Server: JsonObjectRequest
builderOnFailureDialog = new MaterialDialog.Builder(activity)
.title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
.content(onFailureDialogContent)
.positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
.negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
activity.finish();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
onFailureDialog.dismiss();
onSuccessDialog.dismiss();
} catch (Exception e) {
Log.e("Activity.onDestroy()", e.getMessage());
}
}
}
Or is the reason for the problem the async task running in background?
call finish() inside runOnUiThread().
i.e.
replace
finish();
with
runOnUiThread(new Runnable() {
public void run() {
finish()
}
});
I have successfully sent an email in the background and displayed a progress dialog to the user as said email is sent. However when the user flips the screen while the dialog is up I get an IllegalArgumentException. I have tried using a WeakReference object and it doesn't seem to be fixing the problem. This is my AsyncTask class.
private class SendMailTask extends AsyncTask<Mail, String, EmailStatusResponce> {
private final WeakReference<ProgressDialog> weakReference;
public SendMailTask() {
ProgressDialog progressDialog = new ProgressDialog(SendReportActivity.this);
progressDialog.setMessage("Sending...");
progressDialog.setCancelable(false);
progressDialog.show();
weakReference = new WeakReference<>(progressDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected EmailStatusResponce doInBackground(Mail... mail) {
return mail[0].send();
}
#Override
protected void onPostExecute(EmailStatusResponce result) {
super.onPostExecute(result);
if (result != null && weakReference != null) {
weakReference.get().dismiss(); // This is where the exception is thrown.
if (result.isSuccess()) {
Intent intent = new Intent(SendReportActivity.this, MainActivity.class);
startActivity(intent);
}
else {}
}
}
This is the exception
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{688d3e2 V.E...... R......D 0,0-1026,348} not attached to window manager
Thanks in advance for any and all help.
EDIT: More logcat
--------- beginning of crash
12-11 16:22:40.154 1976-1976/com.blazapps.allenfamilymedicine E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blazapps.allenfamilymedicine, PID: 1976
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{f89e667 V.E...... R......D 0,0-760,232} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:424)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:350)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at android.app.Dialog.dismissDialog(Dialog.java:362)
at android.app.Dialog.dismiss(Dialog.java:345)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:168)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:138)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I still do no know why the exception is being thrown but because I save lots of information in EmailStatusResponse I can just surround the exception with a try catch and if the task was complete I get the result I expected.
try {
weakReference.get().dismiss();
} catch (Exception e) {}
If anyone can figure a better solution I would really appreciate it. I hate just catching exceptions. There is usually a better way.
I have implemented an android camera with the help of official developer.android.com tutorial. The app is working fine sometimes but about 3/5 of times the preview of the camera freezes after some rotation and clicking the buttons or even without these works (other elements don't freeze). The cutest part is that when I debug the application the preview doesn't stuck but when I want to run the app normally sometimes the problem happens.
Here is my fullScreen Class which is consist of the codes that android studio generated for fullScreen activity and the codes for implementing surfaceHolder.Callback and camera stuff.
public class CameraActivity extends Activity implements SurfaceHolder.Callback {
... // some constants here
private Camera mCamera;
private SurfaceHolder mHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
SurfaceView cameraSufaceView = (SurfaceView) findViewById(R.id.camera_preview);
// Accessing front camera to take picture
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = cameraSufaceView.getHolder();
mHolder.addCallback(this);
} else {
// Alter user
}
/**
* Gets an instance of front facing camera if available
*/
#SuppressWarnings("deprecation")
private Camera openFrontFacingCameraGingerbread() {
int cameraCount;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
#Override
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(TAG, "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 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
}
// start preview with new settings
try {
// mCamera.setDisplayOrientation(needs degree here);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null)
mCamera = openFrontFacingCameraGingerbread();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
When this problem happens some errors appear in the LogCat but they are not really informative. here are they:
26893-26893/com.naviiid.retinaflash E/art﹕ No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
09-16 01:34:09.336 26893-26893/com.naviiid.retinaflash E/ActivityThread﹕ appStartupEnd :
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
Caused by: java.lang.UnsatisfiedLinkError: No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
at java.lang.Runtime.appStartupEnd(Native Method)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
The only clue that I have found so far is that sometimes android calls onPause method even if the activity isn't paused. For getting instance of the camera again I call openFrontFacingCameraGingerbread() in onResume method.