List of usage examples for android.net Uri fromFile
public static Uri fromFile(File file)
From source file:com.zbrown.droidsteal.activities.UpdateChecker.java
private void InstallFile(String fileName) { Log.d(TAG, "Installing file " + fileName); File file = new File(context.getFilesDir(), fileName); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); activity.startActivity(intent);/*from w w w . j av a 2 s . c o m*/ }
From source file:com.remobile.camera.CameraLauncher.java
/** * Take a picture with the camera./*from w w w .jav a 2 s .c o m*/ * When an image is captured or the camera view is cancelled, the result is returned * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult. * <p/> * The image can either be returned as a base64 string or a URI that points to the file. * To display base64 string in an img tag, set the source to: * img.src="data:image/jpeg;base64,"+result; * or to display URI in an img tag * img.src=result; * * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) * @param returnType Set the type of image to return. */ public void takePicture(int returnType, int encodingType) { // Save the number of images currently on disk for later this.numPics = queryImgDB(whichContentStore()).getCount(); // Let's use the intent and see what happens Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Specify file so that large image is captured and returned File photo = createCaptureFile(encodingType); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); this.imageUri = Uri.fromFile(photo); if (this.cordova != null) { // Let's check to make sure the camera is actually installed. (Legacy Nexus 7 code) PackageManager mPm = this.cordova.getActivity().getPackageManager(); if (intent.resolveActivity(mPm) != null) { this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1); } else { FLog.d(LOG_TAG, "Error: You don't have a default camera. Your device may not be CTS complaint."); } } // else // FLog.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity"); }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
/** * Uploads the specified file to the server URL provided using an HTTP multipart request. * @param source Full path of the file on the file system * @param target URL of the server to receive the file * @param args JSON Array of args * @param callbackContext callback id for optional progress reports * * args[2] fileKey Name of file request parameter * args[3] fileName File name to be used on server * args[4] mimeType Describes file content type * args[5] params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request *//*from w w w. j av a2s . c om*/ private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "upload " + source + " to " + target); // Setup the options final String mimeType = getArgument(args, 4, "image/jpeg"); final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); final boolean trustEveryone = args.optBoolean(6); // Always use chunked mode unless set to false as per API final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); // Look for headers on the params map for backwards compatibility with older Cordova versions. final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); final String objectId = args.getString(9); final String httpMethod = getArgument(args, 10, "POST"); final CordovaResourceApi resourceApi = webView.getResourceApi(); Log.d(LOG_TAG, "mimeType: " + mimeType); Log.d(LOG_TAG, "params: " + params); Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); Log.d(LOG_TAG, "headers: " + headers); Log.d(LOG_TAG, "objectId: " + objectId); Log.d(LOG_TAG, "httpMethod: " + httpMethod); final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); // Accept a path or a URI for the source. Uri tmpSrc = Uri.parse(source); final Uri sourceUri = resourceApi .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); int uriType = CordovaResourceApi.getUriType(targetUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection conn = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; int totalBytes = 0; int fixedLength = -1; try { // Create return object PSFileUploadResult result = new PSFileUploadResult(); PSFileProgressResult progress = new PSFileProgressResult(); //------------------ CLIENT REQUEST // Open a HTTP connection to the URL based on protocol conn = resourceApi.createHttpConnection(targetUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) conn; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod(httpMethod); conn.setRequestProperty("Content-Type", mimeType); // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } // Handle the other headers if (headers != null) { addHeadersToRequest(conn, headers); } // Get a input stream of the file on the phone OpenForReadResult readResult = resourceApi.openForRead(sourceUri); if (readResult.length >= 0) { fixedLength = (int) readResult.length; progress.setLengthComputable(true); progress.setTotal(fixedLength); } Log.d(LOG_TAG, "Content Length: " + fixedLength); // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. // http://code.google.com/p/android/issues/detail?id=3164 // It also causes OOM if HTTPS is used, even on newer devices. boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps); useChunkedMode = useChunkedMode || (fixedLength == -1); if (useChunkedMode) { conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); // Although setChunkedStreamingMode sets this header, setting it explicitly here works // around an OutOfMemoryException when using https. conn.setRequestProperty("Transfer-Encoding", "chunked"); } else { conn.setFixedLengthStreamingMode(fixedLength); } conn.connect(); OutputStream sendStream = null; try { sendStream = conn.getOutputStream(); synchronized (context) { if (context.aborted) { return; } context.currentOutputStream = sendStream; } //We don't want to change encoding, we just want this to write for all Unicode. // create a buffer of maximum size int bytesAvailable = readResult.inputStream.available(); int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); byte[] buffer = new byte[bufferSize]; // read file and write it into form... int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); long prevBytesRead = 0; while (bytesRead > 0) { result.setBytesSent(totalBytes); sendStream.write(buffer, 0, bytesRead); totalBytes += bytesRead; if (totalBytes > prevBytesRead + 102400) { prevBytesRead = totalBytes; Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); } bytesAvailable = readResult.inputStream.available(); bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); // Send a progress event. progress.setLoaded(totalBytes); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } sendStream.flush(); } finally { safeClose(readResult.inputStream); safeClose(sendStream); } context.currentOutputStream = null; Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); //------------------ read the SERVER RESPONSE String responseString; int responseCode = conn.getResponseCode(); Log.d(LOG_TAG, "response code: " + responseCode); Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); TrackingInputStream inStream = null; try { inStream = getInputStream(conn); synchronized (context) { if (context.aborted) { return; } context.currentInputStream = inStream; } ByteArrayOutputStream out = new ByteArrayOutputStream( Math.max(1024, conn.getContentLength())); byte[] buffer = new byte[1024]; int bytesRead = 0; // write bytes to file while ((bytesRead = inStream.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } responseString = out.toString("UTF-8"); } finally { context.currentInputStream = null; safeClose(inStream); } Log.d(LOG_TAG, "got response from server"); Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); // send request and retrieve response result.setResponseCode(responseCode); result.setResponse(responseString); context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } catch (Throwable t) { // Shouldn't happen, but will JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), t); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (conn != null) { // Revert back to the proper verifier and socket factories // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) conn; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } } }); }
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean download(final String source, final File file, final JSONObject headers, final ProgressEvent progress, final CallbackContext callbackContext, final boolean trustEveryone) { Log.d(LOG_TAG, "download " + source); if (!Patterns.WEB_URL.matcher(source).matches()) { sendErrorMessage("Invalid URL", INVALID_URL_ERROR, callbackContext); return false; }/*from w w w .ja v a2 s . c o m*/ final CordovaResourceApi resourceApi = webView.getResourceApi(); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; synchronized (progress) { if (progress.isAborted()) { return false; } } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; PluginResult result = null; TrackingInputStream inputStream = null; boolean cached = false; OutputStream outputStream = null; try { OpenForReadResult readResult = null; final Uri targetUri = resourceApi.remapUri(Uri.fromFile(file)); progress.setTargetFile(file); progress.setStatus(STATUS_DOWNLOADING); Log.d(LOG_TAG, "Download file: " + sourceUri); Log.d(LOG_TAG, "Target file: " + file); Log.d(LOG_TAG, "size = " + file.length()); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // TODO: Make OkHttp use this CookieManager by default. String cookie = getCookies(sourceUri.toString()); if (cookie != null) { connection.setRequestProperty("cookie", cookie); } // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { cached = true; connection.disconnect(); sendErrorMessage("Resource not modified: " + source, CONNECTION_ERROR, callbackContext); return false; } else { if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip int connectionLength = connection.getContentLength(); if (connectionLength != -1) { if (connectionLength > getFreeSpace()) { cached = true; connection.disconnect(); sendErrorMessage("Not enough free space to download", CONNECTION_ERROR, callbackContext); return false; } else { progress.setTotal(connectionLength); } } } inputStream = getInputStream(connection); } } if (!cached) { try { synchronized (progress) { if (progress.isAborted()) { return false; } //progress.connection = connection; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; outputStream = resourceApi.openOutputStream(targetUri); while ((bytesRead = inputStream.read(buffer)) > 0) { synchronized (progress) { if (progress.isAborted()) { return false; } } Log.d(LOG_TAG, "bytes read = " + bytesRead); outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); updateProgress(callbackContext, progress); } } finally { synchronized (progress) { //progress.connection = null; } safeClose(inputStream); safeClose(outputStream); } } } catch (Throwable e) { sendErrorMessage(e.getLocalizedMessage(), CONNECTION_ERROR, callbackContext); } finally { if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } return true; }
From source file:de.appplant.cordova.plugin.emailcomposer.EmailComposer.java
/** * The URI for a resource./*from w w w .j a v a 2 s . c o m*/ * * @param {String} path * The given relative path * * @return The URI pointing to the given path */ private Uri getUriForResourcePath(String path) { String resPath = path.replaceFirst("res://", ""); String fileName = resPath.substring(resPath.lastIndexOf('/') + 1); String resName = fileName.substring(0, fileName.lastIndexOf('.')); String extension = resPath.substring(resPath.lastIndexOf('.')); String storage = cordova.getActivity().getExternalCacheDir().toString() + STORAGE_FOLDER; int resId = getResId(resPath); File file = new File(storage, resName + extension); if (resId == 0) { System.err.println("Attachment resource not found: " + resPath); } new File(storage).mkdir(); try { Resources res = cordova.getActivity().getResources(); FileOutputStream outStream = new FileOutputStream(file); InputStream inputStream = res.openRawResource(resId); copyFile(inputStream, outStream); outStream.flush(); outStream.close(); } catch (Exception e) { e.printStackTrace(); } return Uri.fromFile(file); }
From source file:com.cloverstudio.spika.CameraCropActivity.java
public void startCamera() { // Check if camera exists if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) { Toast.makeText(this, "No camera on device", Toast.LENGTH_LONG).show(); finish();//from w ww . j ava 2 s. com } else { try { long date = System.currentTimeMillis(); String filename = DateFormat.format("yyyy-MM-dd_kk.mm.ss", date).toString() + ".jpg"; _path = this.getExternalCacheDir() + "/" + filename; File file = new File(_path); // File file = new File(getFileDir(getBaseContext()), filename); Uri outputFileUri = Uri.fromFile(file); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(intent, CAMERA); } catch (Exception ex) { Toast.makeText(this, "No camera on device", Toast.LENGTH_LONG).show(); finish(); } } }
From source file:com.richtodd.android.quiltdesign.app.MainActivity.java
private Uri saveRepository() throws RepositoryException { Repository repository = Repository.getDefaultRepository(this); JSONObject targetJsonRepository = new JSONObject(); JSONRepository targetRepository = new JSONRepository(targetJsonRepository, null); targetRepository.merge(repository, MergeModes.New); String name = "Quilt Design Backup - " + s_dateFormat.format(new Date()) + ".quiltdesign"; File file;/*from w ww . ja v a 2 s . c o m*/ try { file = new File(StorageUtility.getPublicFolder(), name); } catch (IOException e) { throw new RepositoryException(e); } JSONUtility.saveJSONObject(file, targetJsonRepository); Uri uri = Uri.fromFile(file); return uri; }
From source file:com.insthub.O2OMobile.Activity.F9_SettingActivity.java
private void showDialog() { LayoutInflater inflater = LayoutInflater.from(this); View view = inflater.inflate(R.layout.photo_dialog, null); mDialog = new Dialog(this, R.style.dialog); mDialog.setContentView(view);/*from ww w .j a va 2 s . c o m*/ mDialog.setCanceledOnTouchOutside(true); mDialog.show(); LinearLayout requsetCameraLayout = (LinearLayout) view.findViewById(R.id.register_camera); LinearLayout requestPhotoLayout = (LinearLayout) view.findViewById(R.id.register_photo); requsetCameraLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mDialog.dismiss(); if (mFileDir == null) { mFileDir = new File(O2OMobileAppConst.FILEPATH + "img/"); if (!mFileDir.exists()) { mFileDir.mkdirs(); } } mFileName = O2OMobileAppConst.FILEPATH + "img/" + "temp.jpg"; mFile = new File(mFileName); Uri imageuri = Uri.fromFile(mFile); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri); intent.putExtra("return-data", false); startActivityForResult(intent, REQUEST_CAMERA); } }); requestPhotoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mDialog.dismiss(); Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(picture, REQUEST_PHOTO); } }); }
From source file:io.strider.camera.CameraLauncher.java
/** * Take a picture with the camera.//from w ww . j ava 2 s. c om * When an image is captured or the camera view is cancelled, the result is returned * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult. * * The image can either be returned as a base64 string or a URI that points to the file. * To display base64 string in an img tag, set the source to: * img.src="data:image/jpeg;base64,"+result; * or to display URI in an img tag * img.src=result; * * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) * @param returnType Set the type of image to return. */ public void takePicture(int returnType, int encodingType) { // Save the number of images currently on disk for later this.numPics = queryImgDB(whichContentStore()).getCount(); // Display camera Intent intent = new Intent(this.cordova.getActivity().getApplicationContext(), CameraActivity.class); // Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // Specify file so that large image is captured and returned File photo = createCaptureFile(encodingType); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); this.imageUri = Uri.fromFile(photo); if (this.cordova != null) { this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1); } // else // LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity"); }
From source file:com.zlkj.dingdangwuyou.activity.CompanyInfoActivity.java
/** * ?// ww w.j a v a 2s. c o m */ private void showAvatarOption() { AlertDialog.Builder builder = new AlertDialog.Builder(this); String[] items = new String[] { "?", "" }; builder.setTitle("").setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(); switch (which) { case 0: // ? if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String curTime = AppTool.dateFormat(System.currentTimeMillis(), "yyyyMMddHHmmss"); // ??? File imagePath = new File(Environment.getExternalStorageDirectory() + Const.APP_IMAGE_PATH); if (!imagePath.exists()) { imagePath.mkdirs(); } cameraFile = new File(imagePath.getPath(), curTime + ".jpg"); intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)); startActivityForResult(intent, Const.REQUEST_CODE_CAMERA); } else { Toast.makeText(context, "???", Toast.LENGTH_SHORT) .show(); } break; case 1: // intent.setAction(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, Const.REQUEST_CODE_GALLERY); break; default: break; } } }); builder.show(); }