Example usage for android.net Uri getScheme

List of usage examples for android.net Uri getScheme

Introduction

In this page you can find the example usage for android.net Uri getScheme.

Prototype

@Nullable
public abstract String getScheme();

Source Link

Document

Gets the scheme of this URI.

Usage

From source file:com.tweetlanes.android.view.HomeActivity.java

void onCreateHandleIntents() {

    boolean turnSoftKeyboardOff = true;

    Intent intent = getIntent();/*from   ww w . j  a v  a  2 s .  c  o m*/
    if (intent.getAction() == Intent.ACTION_SEND) {

        Bundle extras = intent.getExtras();
        String type = intent.getType();
        if (type.equals("text/plain") == true) {

            String shareString = extras.getString(Intent.EXTRA_TEXT);
            if (extras.containsKey(Intent.EXTRA_TEXT)) {
                shareString = extras.getString(Intent.EXTRA_SUBJECT) + " " + shareString;
            }
            beginShareStatus(shareString);

            turnSoftKeyboardOff = false;
        } else if (type.contains("image/")) {
            // From http://stackoverflow.com/a/2641363/328679
            if (extras.containsKey(Intent.EXTRA_STREAM)) {
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                String scheme = uri.getScheme();
                if (scheme.equals("content")) {
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = contentResolver.query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    try {
                        String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
                        beginShareImage(imagePath);
                    } catch (java.lang.IllegalArgumentException e) {
                        Toast.makeText(this, R.string.picture_attach_error, Toast.LENGTH_SHORT).show();
                    }

                    turnSoftKeyboardOff = false;
                }
            }
        }
    }

    if (turnSoftKeyboardOff == true) {
        // Turn the soft-keyboard off. For some reason it wants to appear on screen by default when coming back from multitasking...
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

From source file:com.platform.APIClient.java

public Response sendRequest(Request locRequest, boolean needsAuth, int retryCount) {
    if (retryCount > 1)
        throw new RuntimeException("sendRequest: Warning retryCount is: " + retryCount);
    boolean isTestVersion = BREAD_BUY.equalsIgnoreCase("bread-buy-staging");
    boolean isTestNet = BuildConfig.BITCOIN_TESTNET;
    Request request = locRequest.newBuilder().header("X-Testflight", isTestVersion ? "1" : "0")
            .header("X-Bitcoin-Testnet", isTestNet ? "1" : "0").build();
    if (needsAuth) {
        Request.Builder modifiedRequest = request.newBuilder();
        String base58Body = "";
        RequestBody body = request.body();
        try {/*from   www  .j a va2s. c  o  m*/
            if (body != null && body.contentLength() != 0) {
                BufferedSink sink = new Buffer();
                try {
                    body.writeTo(sink);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String bodyString = sink.buffer().readUtf8();
                base58Body = CryptoHelper.base58ofSha256(bodyString.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String httpDate = sdf.format(new Date());

        request = modifiedRequest.header("Date", httpDate.substring(0, httpDate.length() - 6)).build();

        String queryString = request.url().encodedQuery();

        String requestString = createRequest(request.method(), base58Body, request.header("Content-Type"),
                request.header("Date"), request.url().encodedPath()
                        + ((queryString != null && !queryString.isEmpty()) ? ("?" + queryString) : ""));
        String signedRequest = signRequest(requestString);
        String token = new String(KeyStoreManager.getToken(ctx));
        if (token.isEmpty())
            token = getToken();
        if (token == null || token.isEmpty()) {
            Log.e(TAG, "sendRequest: failed to retrieve token");
            return null;
        }
        String authValue = "bread " + token + ":" + signedRequest;
        //            Log.e(TAG, "sendRequest: authValue: " + authValue);
        modifiedRequest = request.newBuilder();

        request = modifiedRequest.header("Authorization", authValue).build();

    }
    Response response = null;
    byte[] data = new byte[0];
    try {
        OkHttpClient client = new OkHttpClient.Builder().followRedirects(false)
                /*.addInterceptor(new LoggingInterceptor())*/.build();
        //            Log.e(TAG, "sendRequest: before executing the request: " + request.headers().toString());
        response = client.newCall(request).execute();
        try {
            data = response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!response.isSuccessful())
            Log.e(TAG,
                    "sendRequest: "
                            + String.format(Locale.getDefault(), "url (%s), code (%d), mess (%s), body (%s)",
                                    request.url(), response.code(), response.message(), new String(data)));
        if (response.isRedirect()) {
            String newLocation = request.url().scheme() + "://" + request.url().host()
                    + response.header("location");
            Uri newUri = Uri.parse(newLocation);
            if (newUri == null) {
                Log.e(TAG, "sendRequest: redirect uri is null");
            } else if (!newUri.getHost().equalsIgnoreCase(HOST)
                    || !newUri.getScheme().equalsIgnoreCase(PROTO)) {
                Log.e(TAG, "sendRequest: WARNING: redirect is NOT safe: " + newLocation);
            } else {
                Log.w(TAG, "redirecting: " + request.url() + " >>> " + newLocation);
                return sendRequest(new Request.Builder().url(newLocation).get().build(), needsAuth, 0);
            }
            return new Response.Builder().code(500).request(request)
                    .body(ResponseBody.create(null, new byte[0])).protocol(Protocol.HTTP_1_1).build();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return new Response.Builder().code(599).request(request).body(ResponseBody.create(null, new byte[0]))
                .protocol(Protocol.HTTP_1_1).build();
    }

    if (response.header("content-encoding") != null
            && response.header("content-encoding").equalsIgnoreCase("gzip")) {
        Log.d(TAG, "sendRequest: the content is gzip, unzipping");
        byte[] decompressed = gZipExtract(data);
        ResponseBody postReqBody = ResponseBody.create(null, decompressed);

        return response.newBuilder().body(postReqBody).build();
    }
    ResponseBody postReqBody = ResponseBody.create(null, data);
    if (needsAuth && isBreadChallenge(response)) {
        Log.e(TAG, "sendRequest: got authentication challenge from API - will attempt to get token");
        getToken();
        if (retryCount < 1) {
            sendRequest(request, true, retryCount + 1);
        }
    }

    return response.newBuilder().body(postReqBody).build();
}

From source file:com.jamiealtizer.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param usePhoneGap   Load url in PhoneGap webview
 * @return              "" if ok, or error message.
 *//*from   w w w  .jav  a 2s.  co  m*/
public String openExternal(String url) {
    try {
        Intent intent = null;
        intent = new Intent(Intent.ACTION_VIEW);
        // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
        // Adding the MIME type to http: URLs causes them to not be handled by the downloader.
        Uri uri = Uri.parse(url);
        if ("file".equals(uri.getScheme())) {
            intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
        } else {
            intent.setData(uri);
        }
        intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
        this.cordova.getActivity().startActivity(intent);
        return "";
    } catch (android.content.ActivityNotFoundException e) {
        Log.d(LOG_TAG, "InAppBrowser: Error loading url " + url + ":" + e.toString());
        return e.toString();
    }
}

From source file:com.mediatek.galleryfeature.stereo.segment.background.StereoBackgroundActivity.java

private boolean finishIfInvalidUri() {
    if (!mNeedCheckInvalid) {
        return false;
    }/*  www  . j  a  va 2 s .  c o  m*/
    Uri uri = (mMasterImage != null) ? mMasterImage.getUri() : null;
    Intent intent = getIntent();
    if ((uri == null) && (intent != null)) {
        uri = intent.getData();
    }
    MtkLog.d(TAG, "<finishIfInvalidUri> uri:" + uri);
    if (uri != null) {
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return false;
        }
        // fix cursor leak
        final String[] projection = new String[] { ImageColumns.DATA, ImageColumns.CAMERA_REFOCUS };
        android.database.Cursor cursor = null;
        cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) {
            MtkLog.d(TAG, "<finishIfInvalidUri> cannot get cursor for:" + uri);
            return true;
        }
        try {
            if (cursor.moveToNext()) {
                mAbsoluteFilePath = cursor.getString(0);
                MtkLog.d(TAG, "<finishIfInvalidUri> mAbsoluteFilePath = " + mAbsoluteFilePath);
                mIsDepthImage = (cursor.getInt(1) == 1);
                MtkLog.d(TAG, "<finishIfInvalidUri> mIsDepthImage = " + mIsDepthImage);
            } else {
                MtkLog.d(TAG, "<finishIfInvalidUri> cannot find data for: " + uri);
                return true;
            }
        } finally {
            cursor.close();
        }
    }
    return false;
}

From source file:com.example.damerap_ver1.IntroVideoActivity.java

@Override
protected void onCreate(Bundle pSavedInstanceState) {
    super.onCreate(pSavedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // create the layout of the view
    setupView();//from  w  w  w. j a  v a 2s .  c o m

    // determine the messages to be displayed as the view loads the video
    extractMessages();

    // grab a wake-lock so that the video can play without the screen being turned off
    PowerManager lPwrMgr = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = lPwrMgr.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG_WAKELOCK);
    mWakeLock.acquire();

    mProgressMessage.setText(mMsgInit);

    // extract the playlist or video id from the intent that started this video

    Uri lVideoIdUri = this.getIntent().getData();

    if (lVideoIdUri == null) {
        Log.i(this.getClass().getSimpleName(),
                "No video ID was specified in the intent.  Closing video activity.");
        finish();
    }
    String lVideoSchemeStr = lVideoIdUri.getScheme();
    String lVideoIdStr = lVideoIdUri.getEncodedSchemeSpecificPart();
    if (lVideoIdStr == null) {
        Log.i(this.getClass().getSimpleName(),
                "No video ID was specified in the intent.  Closing video activity.");
        finish();
    }
    if (lVideoIdStr.startsWith("//")) {
        if (lVideoIdStr.length() > 2) {
            lVideoIdStr = lVideoIdStr.substring(2);
        } else {
            Log.i(this.getClass().getSimpleName(),
                    "No video ID was specified in the intent.  Closing video activity.");
            finish();
        }
    }

    ///////////////////
    // extract either a video id or a playlist id, depending on the uri scheme
    YouTubeId lYouTubeId = null;
    if (lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_PLAYLIST)) {
        lYouTubeId = new PlaylistId(lVideoIdStr);
    }

    else if (lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_VIDEO)) {
        lYouTubeId = new VideoId(lVideoIdStr);
    }

    if (lYouTubeId == null) {
        Log.i(this.getClass().getSimpleName(),
                "Unable to extract video ID from the intent.  Closing video activity.");
        finish();
    }

    mQueryYouTubeTask = (QueryYouTubeTask) new QueryYouTubeTask().execute(lYouTubeId);
}

From source file:com.shafiq.mytwittle.view.HomeActivity.java

void onCreateHandleIntents() {

    boolean turnSoftKeyboardOff = true;

    Intent intent = getIntent();//  w  w w .j a va 2 s .co m
    if (intent.getAction() == Intent.ACTION_SEND) {

        Bundle extras = intent.getExtras();
        String type = intent.getType();
        if (type.equals("text/plain") == true) {

            String shareString = extras.getString(Intent.EXTRA_TEXT);
            if (extras.containsKey(Intent.EXTRA_TEXT)) {
                shareString = extras.getString(Intent.EXTRA_SUBJECT) + " " + shareString;
            }
            beginShareStatus(shareString);

            turnSoftKeyboardOff = false;
        } else if (type.contains("image/")) {
            // From http://stackoverflow.com/a/2641363/328679
            if (extras.containsKey(Intent.EXTRA_STREAM)) {
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                String scheme = uri.getScheme();
                if (scheme.equals("content")) {
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = contentResolver.query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    try {
                        String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
                        beginShareImage(imagePath);
                    } catch (java.lang.IllegalArgumentException e) {
                        Toast.makeText(this, R.string.picture_attach_error, Toast.LENGTH_SHORT).show();
                    }

                    turnSoftKeyboardOff = false;
                }
            }
        }
    }

    if (turnSoftKeyboardOff == true) {
        // Turn the soft-keyboard off. For some reason it wants to appear on
        // screen by default when coming back from multitasking...
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

From source file:com.android.contacts.common.model.ContactLoader.java

/**
 * Looks for the photo data item in entities. If found, a thumbnail will be stored. A larger
 * photo will also be stored if available.
 *///from www  . j av  a2  s . com
private void loadPhotoBinaryData(Contact contactData) {
    loadThumbnailBinaryData(contactData);

    // Try to load the large photo from a file using the photo URI.
    String photoUri = contactData.getPhotoUri();
    if (photoUri != null) {
        try {
            final InputStream inputStream;
            final AssetFileDescriptor fd;
            final Uri uri = Uri.parse(photoUri);
            final String scheme = uri.getScheme();
            if ("http".equals(scheme) || "https".equals(scheme)) {
                // Support HTTP urls that might come from extended directories
                inputStream = new URL(photoUri).openStream();
                fd = null;
            } else {
                fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
                inputStream = fd.createInputStream();
            }
            byte[] buffer = new byte[16 * 1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                int size;
                while ((size = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, size);
                }
                contactData.setPhotoBinaryData(baos.toByteArray());
            } finally {
                inputStream.close();
                if (fd != null) {
                    fd.close();
                }
            }
            return;
        } catch (IOException ioe) {
            // Just fall back to the case below.
        }
    }

    // If we couldn't load from a file, fall back to the data blob.
    contactData.setPhotoBinaryData(contactData.getThumbnailPhotoBinaryData());
}

From source file:com.netcompss.ffmpeg4android_client.BaseVideo.java

public String getFileNameByUri(Context context, Uri uri) {
    String fileName = "unknown";// default fileName
    Uri filePathUri = uri;/*ww  w  . jav  a2s .com*/
    if (uri.getScheme().toString().compareTo("content") == 0) {
        ParcelFileDescriptor parcelFileDescriptor;
        String filename = null;
        try {
            FileOutputStream fos = null;
            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/CHURCH");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            } else {
                mFolder.delete();
                mFolder.mkdir();
            }

            String s = "rough.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            filename = f.getAbsolutePath();
            Log.d("f", filename);
            try {
                fos = new FileOutputStream(f);
                image.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            } catch (Exception e) {

                e.printStackTrace();
            }
            parcelFileDescriptor.close();
            return filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (uri.getScheme().compareTo("file") == 0) {
        fileName = filePathUri.getPath();
        File fill = new File(fileName);
        if (fill.exists()) {
            Log.d("exitst", "exist");
            ParcelFileDescriptor parcelFileDescriptor;
            String filename = null;
            FileOutputStream fos = null;
            Bitmap image = BitmapFactory.decodeFile(fileName);
            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/CHURCH");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            } else {
                mFolder.delete();
                mFolder.mkdir();
            }

            String s = "rough.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            filename = f.getAbsolutePath();
            Log.d("f", filename);
            try {
                fos = new FileOutputStream(f);
                image.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            } catch (Exception e) {

                e.printStackTrace();
            }
        } else {
            Log.d("not file exitst", "not exist");
        }
        Log.d("file", "file");
    } else {
        fileName = filePathUri.getPath();
        Log.d("else", "else");
    }

    return fileName;

}

From source file:com.tweetlanes.android.core.view.HomeActivity.java

void onCreateHandleIntents() {

    boolean turnSoftKeyboardOff = true;

    Intent intent = getIntent();//from w w  w . ja  v a  2 s .c o m

    Bundle extras = intent.getExtras();

    if (extras != null) {
        String type = intent.getType();
        if (intent.getAction() == Intent.ACTION_SEND && type != null) {

            if (type.equals("text/plain") && extras.containsKey(Intent.EXTRA_TEXT)) {

                String shareString = extras.getString(Intent.EXTRA_TEXT);
                if (extras.containsKey(Intent.EXTRA_SUBJECT)) {
                    shareString = extras.getString(Intent.EXTRA_SUBJECT) + " " + shareString;
                }
                beginShareStatus(shareString);

                turnSoftKeyboardOff = false;

            } else if (type.contains("image/")) {
                // From http://stackoverflow.com/a/2641363/328679
                if (extras.containsKey(Intent.EXTRA_STREAM)) {
                    Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
                    String scheme = uri.getScheme();
                    if (scheme.equals("content")) {
                        ContentResolver contentResolver = getContentResolver();
                        Cursor cursor = contentResolver.query(uri, null, null, null, null);
                        cursor.moveToFirst();
                        try {
                            String imagePath = cursor
                                    .getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
                            beginShareImage(imagePath);
                        } catch (java.lang.IllegalArgumentException e) {
                            Toast.makeText(this, R.string.picture_attach_error, Toast.LENGTH_SHORT).show();
                        } finally {
                            cursor.close();
                            cursor = null;
                        }

                        turnSoftKeyboardOff = false;
                    }
                }
            }
        }
    }

    if (turnSoftKeyboardOff) {
        // Turn the soft-keyboard off. For some reason it wants to appear on
        // screen by default when coming back from multitasking...
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

From source file:Main.java

@SuppressLint("NewApi")
public static String getRealPath(Context context, Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        if (URI_EXTERNAL_DOCUMENTS.equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }/* w  w w .  j  a  v a2 s.  co m*/
        } else if (URI_DOWNLOAD_DOCUMENTS.equals(uri.getAuthority())) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        } else if (URI_MEDIA_DOCUMENTS.equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        if (URI_GOOGLE_PHOTOS.equals(uri.getAuthority()))
            return uri.getLastPathSegment();
        return getDataColumn(context, uri, null, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}