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:maimeng.yodian.app.client.android.chat.activity.ChatActivity.java

/**
 * ??//from   w  w w  .  ja  v a 2  s .c o  m
 *
 * @param uri
 */
private void sendFile(Uri uri) {
    String filePath = null;
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        filePath = uri.getPath();
    }
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        String st7 = getResources().getString(R.string.File_does_not_exist);
        Toast.makeText(getApplicationContext(), st7, Toast.LENGTH_SHORT).show();
        return;
    }
    if (file.length() > 10 * 1024 * 1024) {
        String st6 = getResources().getString(R.string.The_file_is_not_greater_than_10_m);
        Toast.makeText(getApplicationContext(), st6, Toast.LENGTH_SHORT).show();
        return;
    }

    // ?
    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
    setExtAttribute(message, MESSAGE_FILE);

    message.setReceipt(toChatUsername);
    // add message body
    NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
    message.addBody(body);
    if (isRobot) {
        message.setAttribute("em_robot_message", true);
    }
    conversation.addMessage(message);
    onNewMessage(message);
    listView.setAdapter(adapter);
    adapter.refreshSelectLast();
    setResult(RESULT_OK);
}

From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java

private boolean delete(Uri uri) {
    if (uri.getScheme().equals("content")) {
        int deleted = getContentResolver().delete(uri, null, null);
        return deleted == 1;
    }//from w ww .j  a v a2  s.co  m
    if (uri.getScheme().equals("file")) {
        java.io.File file = new java.io.File(uri.toString().substring(5));
        return file.delete();
    }
    return false;
}

From source file:com.kdao.cmpe235_project.UploadActivity.java

@SuppressLint("NewApi")
private String getPath(Uri uri) throws URISyntaxException {
    final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
    String selection = null;/*ww w. j  a  va2 s . co  m*/
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    // deal with different Uris.
    if (needToCheckUri && DocumentsContract.isDocumentUri(getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(Uri.parse(LOCAL_FOLDER_PATH), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[] { split[1] };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

From source file:com.github.pockethub.android.accounts.LoginWebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView webView = new WebView(this);

    // Needs the be activated to allow GitHub to perform their requests.
    webView.getSettings().setJavaScriptEnabled(true);

    String userAgent = webView.getSettings().getUserAgentString();
    // Remove chrome from the user agent since GitHub checks it incorrectly
    userAgent = userAgent.replaceAll("Chrome/\\d{2}\\.\\d\\.\\d\\.\\d", "");
    webView.getSettings().setUserAgentString(userAgent);

    String url = getIntent().getStringExtra(LoginActivity.INTENT_EXTRA_URL);
    webView.loadUrl(url);/*from ww w . j  a va2 s  .  com*/

    webView.setWebViewClient(new WebViewClient() {
        MaterialDialog dialog = new MaterialDialog.Builder(LoginWebViewActivity.this).content(R.string.loading)
                .progress(true, 0).build();

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            dialog.show();
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            dialog.dismiss();
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(android.webkit.WebView view,
                WebResourceRequest request) {
            return shouldIntercept(request.getUrl().toString());
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(android.webkit.WebView view, String url) {
            return shouldIntercept(url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            Uri uri = Uri.parse(url);
            return overrideOAuth(uri) || super.shouldOverrideUrlLoading(view, url);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {

            return overrideOAuth(request.getUrl()) || super.shouldOverrideUrlLoading(view, request);
        }

        /**
         * This method will inject polyfills to the auth javascript if the version is
         * below Lollipop. After Lollipop WebView is updated via the Play Store so the polyfills
         * are not needed.
         *
         * @param url The requests url
         * @return null if there request should not be altered or a new response
         *     instance with polyfills.
         */
        private WebResourceResponse shouldIntercept(String url) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                return null;
            }

            if (url.matches(".*frameworks.*.js")) {
                InputStream in1 = null;
                InputStream in2 = null;
                Response response = null;
                try {
                    response = new OkHttpClient.Builder().build()
                            .newCall(new Request.Builder().get().url(url).build()).execute();

                    if (response.body() != null) {
                        in1 = response.body().byteStream();
                    }

                    in2 = getAssets().open("polyfills.js");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (response == null) {
                    return null;
                }

                SequenceInputStream inputStream = new SequenceInputStream(in2, in1);
                return new WebResourceResponse("text/javascript", "utf-8", inputStream);
            } else {
                return null;
            }
        }

        private boolean overrideOAuth(Uri uri) {
            if (uri.getScheme().equals(getString(R.string.github_oauth_scheme))) {
                Intent data = new Intent();
                data.setData(uri);
                setResult(RESULT_OK, data);
                finish();
                return true;
            }

            return false;
        }
    });

    setContentView(webView);
}

From source file:com.lgallardo.youtorrentcontroller.RefreshListener.java

public static String getFilePathFromUri(Context c, Uri uri) {
    String filePath = null;/*w w  w.  j ava 2s .  co m*/
    if ("content".equals(uri.getScheme())) {
        String[] filePathColumn = { MediaStore.MediaColumns.DATA };
        ContentResolver contentResolver = c.getContentResolver();

        Cursor cursor = contentResolver.query(uri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
    } else if ("file".equals(uri.getScheme())) {
        filePath = new File(uri.getPath()).getAbsolutePath();
    }
    return filePath;
}

From source file:com.stfalcon.contentmanager.ContentManager.java

@TargetApi(Build.VERSION_CODES.KITKAT)
private String getFilePath(String originalPath) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    Uri uri = Uri.parse(originalPath);
    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(activity, uri)) {
        // ExternalStorageProvider
        if (isFileDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getFileData(contentUri, null, null);
        }/* w  w  w . j  a  va 2s .c o m*/
        // MediaProvider
        else if (isFileMediaDocument(uri)) {
            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 getFileData(contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getFileData(uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:im.neon.activity.LoginActivity.java

/**
 * Check if the client supports the registration kind.
 *
 * @param registrationFlowResponse the response
 *//*from  www. j a  v  a 2s. c o m*/
private void onRegistrationFlow(RegistrationFlowResponse registrationFlowResponse) {
    enableLoadingScreen(false);
    setActionButtonsEnabled(true);

    mRegistrationResponse = registrationFlowResponse;

    // Check whether all listed flows in this authentication session are supported
    // We suggest using the fallback page (if any), when at least one flow is not supported.
    if (RegistrationManager.getInstance().hasNonSupportedStage()) {
        String hs = getHomeServerUrl();
        boolean validHomeServer = false;

        try {
            Uri hsUri = Uri.parse(hs);
            validHomeServer = "http".equals(hsUri.getScheme()) || "https".equals(hsUri.getScheme());
        } catch (Exception e) {
            Log.e(LOG_TAG, "## Exception: " + e.getMessage());
        }

        if (!validHomeServer) {
            Toast.makeText(LoginActivity.this, getString(R.string.login_error_invalid_home_server),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        fallbackToLoginMode();

        Intent intent = new Intent(LoginActivity.this, AccountCreationActivity.class);
        intent.putExtra(AccountCreationActivity.EXTRA_HOME_SERVER_ID, hs);
        startActivityForResult(intent, ACCOUNT_CREATION_ACTIVITY_REQUEST_CODE);
    }
}

From source file:com.android.mms.ui.MessageUtils.java

public static String checkAndModifyUrl(String url) {
    if (url == null) {
        return null;
    }//from   www.j av  a  2 s .c om

    Uri uri = Uri.parse(url);
    if (uri.getScheme() != null) {
        return url;
    }

    return "http://" + url;
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
* From://from  w  w  w . j  a v a  2  s . c  o  m
* https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
*
* MODIFIED FOR MAGE:
*
* - Removed LocalStorageProvider references
* - Added and modified to use isDocumentUri and getDocumentId methods with KITKAT target api annotation
* - Added ExternalStorageProvider SD card handler section in the getPath method
* - Added getFileIfExists method
*
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 * 
 * @param context The context.
 * @param uri The Uri to query.
* @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && isDocumentUri(context, uri)) {

        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // Handle SD cards
            File file = getFileIfExists("/storage/extSdCard", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/sdcard1", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/usbcard1", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/sdcard0", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = 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);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}