Search in sources :

Example 71 with AsyncTask

use of android.os.AsyncTask in project OpenCamera by ageback.

the class Preview method openCamera.

// private int debug_count_opencamera = 0; // see usage below
/**
 * Try to open the camera. Should only be called if camera_controller==null.
 *  The camera will be opened on a background thread, so won't be available upon
 *  exit of this function.
 *  If camera_open_state is already CAMERAOPENSTATE_OPENING, this method does nothing.
 */
private void openCamera() {
    long debug_time = 0;
    if (MyDebug.LOG) {
        Log.d(TAG, "openCamera()");
        debug_time = System.currentTimeMillis();
    }
    if (camera_open_state == CameraOpenState.CAMERAOPENSTATE_OPENING) {
        if (MyDebug.LOG)
            Log.d(TAG, "already opening camera in background thread");
        return;
    } else if (camera_open_state == CameraOpenState.CAMERAOPENSTATE_CLOSING) {
        Log.d(TAG, "tried to open camera while camera is still closing in background thread");
        return;
    }
    // need to init everything now, in case we don't open the camera (but these may already be initialised from an earlier call - e.g., if we are now switching to another camera)
    // n.b., don't reset has_set_location, as we can remember the location when switching camera
    // theoretically should be false anyway, but I had one RuntimeException from surfaceCreated()->openCamera()->setupCamera()->setPreviewSize() because is_preview_started was true, even though the preview couldn't have been started
    is_preview_started = false;
    set_preview_size = false;
    preview_w = 0;
    preview_h = 0;
    has_focus_area = false;
    focus_success = FOCUS_DONE;
    focus_started_time = -1;
    synchronized (this) {
        // synchronise for consistency (keep FindBugs happy)
        take_photo_after_autofocus = false;
    // no need to call camera_controller.setCaptureFollowAutofocusHint() as we're opening the camera
    }
    set_flash_value_after_autofocus = "";
    successfully_focused = false;
    preview_targetRatio = 0.0;
    scene_modes = null;
    has_zoom = false;
    max_zoom_factor = 0;
    minimum_focus_distance = 0.0f;
    zoom_ratios = null;
    faces_detected = null;
    supports_face_detection = false;
    using_face_detection = false;
    supports_video_stabilization = false;
    supports_photo_video_recording = false;
    can_disable_shutter_sound = false;
    color_effects = null;
    white_balances = null;
    isos = null;
    supports_white_balance_temperature = false;
    min_temperature = 0;
    max_temperature = 0;
    supports_iso_range = false;
    min_iso = 0;
    max_iso = 0;
    supports_exposure_time = false;
    min_exposure_time = 0L;
    max_exposure_time = 0L;
    exposures = null;
    min_exposure = 0;
    max_exposure = 0;
    exposure_step = 0.0f;
    supports_expo_bracketing = false;
    max_expo_bracketing_n_images = 0;
    supports_raw = false;
    supports_burst = false;
    // set a sensible default
    view_angle_x = 55.0f;
    // set a sensible default
    view_angle_y = 43.0f;
    sizes = null;
    current_size_index = -1;
    has_capture_rate_factor = false;
    capture_rate_factor = 1.0f;
    video_high_speed = false;
    supports_video = true;
    supports_video_high_speed = false;
    video_quality_handler.resetCurrentQuality();
    supported_flash_values = null;
    current_flash_index = -1;
    supported_focus_values = null;
    current_focus_index = -1;
    max_num_focus_areas = 0;
    applicationInterface.cameraInOperation(false, false);
    if (is_video)
        applicationInterface.cameraInOperation(false, true);
    if (!this.has_surface) {
        if (MyDebug.LOG) {
            Log.d(TAG, "preview surface not yet available");
        }
        return;
    }
    if (this.app_is_paused) {
        if (MyDebug.LOG) {
            Log.d(TAG, "don't open camera as app is paused");
        }
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // we restrict the checks to Android 6 or later just in case, see note in LocationSupplier.setupLocationListener()
        if (MyDebug.LOG)
            Log.d(TAG, "check for permissions");
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (MyDebug.LOG)
                Log.d(TAG, "camera permission not available");
            has_permissions = false;
            applicationInterface.requestCameraPermission();
            // return for now - the application should try to reopen the camera if permission is granted
            return;
        }
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (MyDebug.LOG)
                Log.d(TAG, "storage permission not available");
            has_permissions = false;
            applicationInterface.requestStoragePermission();
            // return for now - the application should try to reopen the camera if permission is granted
            return;
        }
        if (MyDebug.LOG)
            Log.d(TAG, "permissions available");
    }
    // set in case this was previously set to false
    has_permissions = true;
    /*{
			// debug
			if( debug_count_opencamera++ == 0 ) {
				if( MyDebug.LOG )
					Log.d(TAG, "debug: don't open camera yet");
				return;
			}
		}*/
    camera_open_state = CameraOpenState.CAMERAOPENSTATE_OPENING;
    int cameraId = applicationInterface.getCameraIdPref();
    if (cameraId < 0 || cameraId >= camera_controller_manager.getNumberOfCameras()) {
        if (MyDebug.LOG)
            Log.d(TAG, "invalid cameraId: " + cameraId);
        cameraId = 0;
        applicationInterface.setCameraIdPref(cameraId);
    }
    // final boolean use_background_thread = false;
    // final boolean use_background_thread = true;
    final boolean use_background_thread = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
    /* Opening camera on background thread is important so that we don't block the UI thread:
		 *   - For old Camera API, this is recommended behaviour by Google for Camera.open().
		     - For Camera2, the manager.openCamera() call is asynchronous, but CameraController2
		       waits for it to open, so it's still important that we run that in a background thread.
		 * In theory this works for all Android versions, but this caused problems of Galaxy Nexus
		 * with tests testTakePhotoAutoLevel(), testTakePhotoAutoLevelAngles() (various camera
		 * errors/exceptions, failing to taking photos). Since this is a significant change, this is
		 * for now limited to modern devices.
		 */
    if (use_background_thread) {
        final int cameraId_f = cameraId;
        open_camera_task = new AsyncTask<Void, Void, CameraController>() {

            private static final String TAG = "Preview/openCamera";

            @Override
            protected CameraController doInBackground(Void... voids) {
                if (MyDebug.LOG)
                    Log.d(TAG, "doInBackground, async task: " + this);
                return openCameraCore(cameraId_f);
            }

            /**
             * The system calls this to perform work in the UI thread and delivers
             * the result from doInBackground()
             */
            protected void onPostExecute(CameraController camera_controller) {
                if (MyDebug.LOG)
                    Log.d(TAG, "onPostExecute, async task: " + this);
                // see note in openCameraCore() for why we set camera_controller here
                Preview.this.camera_controller = camera_controller;
                cameraOpened();
                // set camera_open_state after cameraOpened, just in case a non-UI thread is listening for this - also
                // important for test code waitUntilCameraOpened(), as test code runs on a different thread
                camera_open_state = CameraOpenState.CAMERAOPENSTATE_OPENED;
                // just to be safe
                open_camera_task = null;
                if (MyDebug.LOG)
                    Log.d(TAG, "onPostExecute done, async task: " + this);
            }

            protected void onCancelled(CameraController camera_controller) {
                if (MyDebug.LOG) {
                    Log.d(TAG, "onCancelled, async task: " + this);
                    Log.d(TAG, "camera_controller: " + camera_controller);
                }
                // dispose of the camera controller
                if (camera_controller != null) {
                    // this is the local camera_controller, not Preview.this.camera_controller!
                    camera_controller.release();
                }
                // n.b., still set OPENED state - important for test thread to know that this callback is complete
                camera_open_state = CameraOpenState.CAMERAOPENSTATE_OPENED;
                // just to be safe
                open_camera_task = null;
                if (MyDebug.LOG)
                    Log.d(TAG, "onCancelled done, async task: " + this);
            }
        }.execute();
    } else {
        this.camera_controller = openCameraCore(cameraId);
        if (MyDebug.LOG) {
            Log.d(TAG, "openCamera: time after opening camera: " + (System.currentTimeMillis() - debug_time));
        }
        cameraOpened();
        camera_open_state = CameraOpenState.CAMERAOPENSTATE_OPENED;
    }
    if (MyDebug.LOG) {
        Log.d(TAG, "openCamera: total time to open camera: " + (System.currentTimeMillis() - debug_time));
    }
}
Also used : CameraController(net.sourceforge.opencamera.CameraController.CameraController) AsyncTask(android.os.AsyncTask) Paint(android.graphics.Paint) Point(android.graphics.Point)

Example 72 with AsyncTask

use of android.os.AsyncTask in project Meltdown by phubbard.

the class RestClient method callUserURL.

// Call the users' hook URL, async. Ignore response and/or errors.
protected void callUserURL(final String user_url) {
    class mTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                HttpURLConnection connection;
                URL uurl = new URL(user_url);
                connection = (HttpURLConnection) uurl.openConnection();
                connection.connect();
                connection.disconnect();
                // fcc.close();
                return null;
            } catch (MalformedURLException e) {
                Log.e(TAG, "User URL badly formed, cannot invoke", e);
            } catch (IOException e) {
                Log.e(TAG, "Error on user hook call", e);
            }
            return null;
        }
    }
    new mTask().execute();
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) AsyncTask(android.os.AsyncTask) IOException(java.io.IOException) URL(java.net.URL)

Example 73 with AsyncTask

use of android.os.AsyncTask in project Meltdown by phubbard.

the class RestClient method verifyLogin.

// Verify that our credentials are correct by opening the API URL. If they are,
// we'll get 'auth:1' in the result. We also check for the min API version (3).
public Boolean verifyLogin() {
    login_ok = false;
    condv = new ConditionVariable();
    class ltask extends AsyncTask<Void, Void, Void> {

        protected Void doInBackground(Void... params) {
            setLoginResult(checkAuth());
            return null;
        }
    }
    new ltask().execute();
    if (!condv.block(10000L))
        Log.w(TAG, "Timed out on login check!");
    return login_ok;
}
Also used : ConditionVariable(android.os.ConditionVariable) AsyncTask(android.os.AsyncTask)

Example 74 with AsyncTask

use of android.os.AsyncTask in project android_packages_apps_Gallery2 by LineageOS.

the class GalleryProvider method openPipeHelper.

// Modified from ContentProvider.openPipeHelper. We are target at API LEVEL 10.
// But openPipeHelper is available in API LEVEL 11.
private static <T> ParcelFileDescriptor openPipeHelper(final T args, final PipeDataWriter<T> func) throws FileNotFoundException {
    try {
        final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
        AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {

            @Override
            protected Object doInBackground(Object... params) {
                try {
                    func.writeDataToPipe(pipe[1], args);
                    return null;
                } finally {
                    Utils.closeSilently(pipe[1]);
                }
            }
        };
        AsyncTaskUtil.executeInParallel(task, (Object[]) null);
        return pipe[0];
    } catch (IOException e) {
        throw new FileNotFoundException("failure making pipe");
    }
}
Also used : ParcelFileDescriptor(android.os.ParcelFileDescriptor) AsyncTask(android.os.AsyncTask) FileNotFoundException(java.io.FileNotFoundException) MediaObject(com.android.gallery3d.data.MediaObject) IOException(java.io.IOException)

Example 75 with AsyncTask

use of android.os.AsyncTask in project MDM-Android-Agent by wso2-attic.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    setContentView(R.layout.activity_main);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    demoDeviceAdmin = new ComponentName(this, WSO2DeviceAdminReceiver.class);
    context = this;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey(getResources().getString(R.string.intent_extra_regid))) {
            regId = extras.getString(getResources().getString(R.string.intent_extra_regid));
        }
        if (extras.containsKey(getResources().getString(R.string.intent_extra_email))) {
            email = extras.getString(getResources().getString(R.string.intent_extra_email));
        }
    }
    if (regId.equals("") || regId == null) {
        GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
    }
    if (GCMRegistrar.isRegisteredOnServer(this)) {
        regId = GCMRegistrar.getRegistrationId(this);
    }
    SharedPreferences mainPref = this.getSharedPreferences(getResources().getString(R.string.shared_pref_package), Context.MODE_PRIVATE);
    Editor editor = mainPref.edit();
    editor.putString(getResources().getString(R.string.shared_pref_username), email);
    editor.commit();
    // Enroll automatically
    final Context context = MainActivity.this;
    mRegisterTask = new AsyncTask<Void, Void, String>() {

        @Override
        protected String doInBackground(Void... params) {
            // ServerUtilities.register(context, regId);
            try {
                regState = ServerUtilities.register(regId, context);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        ProgressDialog progressDialog;

        // declare other objects as per your need
        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this, getResources().getString(R.string.dialog_enrolling), getResources().getString(R.string.dialog_please_wait), true);
        // do initialization of required objects objects here
        }

        @Override
        protected void onPostExecute(String result) {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            if (regState) {
                Intent intent = new Intent(MainActivity.this, AlreadyRegisteredActivity.class);
                intent.putExtra(getResources().getString(R.string.intent_extra_regid), regId);
                intent.putExtra(getResources().getString(R.string.intent_extra_fresh_reg_flag), true);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            // finish();
            } else {
                Intent intent = new Intent(MainActivity.this, AuthenticationErrorActivity.class);
                intent.putExtra(getResources().getString(R.string.intent_extra_regid), regId);
                intent.putExtra(getResources().getString(R.string.intent_extra_from_activity), MainActivity.class.getSimpleName());
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            // finish();
            }
            // }else{
            // btnLayout.setVisibility(View.VISIBLE);
            // progressDialog.dismiss();
            // }
            mRegisterTask = null;
        }
    };
    mRegisterTask.execute(null, null, null);
    btnEnroll = (Button) findViewById(R.id.btnEnroll);
    btnLayout = (RelativeLayout) findViewById(R.id.enrollPanel);
    // ImageView optionBtn = (ImageView) findViewById(R.id.option_button);
    btnEnroll.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mRegisterTask = new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... params) {
                    // ServerUtilities.register(context, regId);
                    try {
                        regState = ServerUtilities.register(regId, context);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                ProgressDialog progressDialog;

                // declare other objects as per your need
                @Override
                protected void onPreExecute() {
                    progressDialog = ProgressDialog.show(MainActivity.this, getResources().getString(R.string.dialog_enrolling), getResources().getString(R.string.dialog_please_wait), true);
                // do initialization of required objects objects here
                }

                @Override
                protected void onPostExecute(String result) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (regState) {
                        Intent intent = new Intent(MainActivity.this, AlreadyRegisteredActivity.class);
                        intent.putExtra(getResources().getString(R.string.intent_extra_regid), regId);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    // finish();
                    } else {
                        Intent intent = new Intent(MainActivity.this, AuthenticationErrorActivity.class);
                        intent.putExtra(getResources().getString(R.string.intent_extra_regid), regId);
                        intent.putExtra(getResources().getString(R.string.intent_extra_from_activity), MainActivity.class.getSimpleName());
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    // finish();
                    }
                    // }else{
                    // btnLayout.setVisibility(View.VISIBLE);
                    // progressDialog.dismiss();
                    // }
                    mRegisterTask = null;
                }
            };
            mRegisterTask.execute(null, null, null);
        }
    });
/*btnEnroll.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				final Context context = MainActivity.this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                      //  boolean registered = ServerUtilities.register(context, regId);
                    //	ServerUtilities.register(context, regId);
                    	ServerUtilities.register(regId, context);
                    	
                    	return null;
                    }

                    ProgressDialog progressDialog;
                    //declare other objects as per your need
                    @Override
                    protected void onPreExecute()
                    {
                        progressDialog= ProgressDialog.show(MainActivity.this, "Enrolling Device","Please wait", true);

                        //do initialization of required objects objects here                
                    }; 
                    @Override
                    protected void onPostExecute(Void result) {
                		//Direct to register successful class
	                    	Intent intent = new Intent(MainActivity.this,RegisterSuccessful.class);
	                    	intent.putExtra("regid", regId);
	                    	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                    	startActivity(intent);
	                    	finish();
                        mRegisterTask = null;
                        //progressDialog.dismiss();
                    }

                };
                mRegisterTask.execute(null, null, null);
				
			}
		});*/
}
Also used : Context(android.content.Context) WSO2DeviceAdminReceiver(com.wso2.mobile.mdm.services.WSO2DeviceAdminReceiver) SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ProgressDialog(android.app.ProgressDialog) TextView(android.widget.TextView) View(android.view.View) OnClickListener(android.view.View.OnClickListener) ComponentName(android.content.ComponentName) Editor(android.content.SharedPreferences.Editor)

Aggregations

AsyncTask (android.os.AsyncTask)394 IOException (java.io.IOException)188 InputStream (java.io.InputStream)159 URL (java.net.URL)159 HttpURLConnection (java.net.HttpURLConnection)158 ExecutionException (java.util.concurrent.ExecutionException)158 Gson (com.google.gson.Gson)155 Message (com.remswork.project.alice.model.support.Message)153 GradingFactorException (com.remswork.project.alice.exception.GradingFactorException)102 ArrayList (java.util.ArrayList)93 View (android.view.View)54 Intent (android.content.Intent)52 TextView (android.widget.TextView)52 JSONException (org.json.JSONException)51 JSONArray (org.json.JSONArray)50 DialogInterface (android.content.DialogInterface)40 OutputStream (java.io.OutputStream)37 BufferedWriter (java.io.BufferedWriter)35 OutputStreamWriter (java.io.OutputStreamWriter)35 ImageView (android.widget.ImageView)33