Example usage for android.content Intent setDataAndType

List of usage examples for android.content Intent setDataAndType

Introduction

In this page you can find the example usage for android.content Intent setDataAndType.

Prototype

public @NonNull Intent setDataAndType(@Nullable Uri data, @Nullable String type) 

Source Link

Document

(Usually optional) Set the data for the intent along with an explicit MIME data type.

Usage

From source file:it.telecomitalia.my.base_struct_apps.VersionUpdate.java

@Override
protected Void doInBackground(String... urls) {
    /* metodo principale per aggiornamento */
    String xml = "";
    try {// w ww .  ja  va  2  s. c  o  m
        /* tento di leggermi il file XML remoto */
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
        /* ora in xml c' il codice della pagina degli aggiornamenti */
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile
    try {
        /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti.
        * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione  la
        * applicazione sul server.*/
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Document dom = db.parse(is);
        Element element = dom.getDocumentElement();
        Element current = (Element) element.getElementsByTagName("current").item(0);
        currentVersion = current.getAttribute("value");
        currentApkName = current.getAttribute("apk");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi
    * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo
    * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */
    if (currentVersion != null & runningVersion != null) {
        /* esistono, li trasformo in double */
        Double serverVersion = Double.parseDouble(currentVersion);
        Double localVersion = Double.parseDouble(runningVersion);
        /* La versione server  superiore alla mia ! Occorre aggiornare */
        if (serverVersion > localVersion) {
            try {
                /* connessione al server */
                URL urlAPK = new URL(SERVER + PATH + currentApkName);
                HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection();
                con.setRequestMethod("GET");
                con.setDoOutput(true);
                con.connect();
                // qual' la tua directory di sistema Download ?
                File downloadPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File outputFile = new File(downloadPath, currentApkName);
                //Log.i("test", downloadPath.getAbsolutePath());
                //Log.i("test", outputFile.getAbsolutePath());
                // se esistono download parziali o vecchi, li elimino.
                if (outputFile.exists())
                    outputFile.delete();
                /* mi creo due File Stream uno di input, quello che sto scaricando dal server,
                * e l'altro di output, quello che sto creando nella directory Download*/
                InputStream input = con.getInputStream();
                FileOutputStream output = new FileOutputStream(outputFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.close();
                input.close();
                /* una volta terminato il processo, attraverso un intent lancio il file che ho
                * appena scaricato in modo da installare immediatamente l'aggiornamento come
                * specificato qui
                * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.f2prateek.dfg.ui.activities.MainActivity.java

@Subscribe
public void onMultipleImagesProcessed(final Events.MultipleImagesProcessed event) {
    if (event.uriList.size() == 0) {
        return;//  ww  w .  j a  va  2 s. c  o  m
    }
    Snackbar.make(pager,
            getString(R.string.multiple_screenshots_saved, event.uriList.size(), event.device.name()),
            Snackbar.LENGTH_LONG).setAction(R.string.open, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent launchIntent = new Intent(Intent.ACTION_VIEW);
                    launchIntent.setDataAndType(event.uriList.get(0), "image/png");
                    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(launchIntent);
                }
            }).show();
}

From source file:com.amaze.filemanager.utils.files.FileUtils.java

/**
 * Open file from OTG/*from  w w  w  . j  av  a 2s .  c om*/
 */
public static void openunknown(DocumentFile f, Context c, boolean forcechooser, boolean useNewStack) {
    Intent chooserIntent = new Intent();
    chooserIntent.setAction(Intent.ACTION_VIEW);
    chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        chooserIntent.setDataAndType(f.getUri(), type);
        Intent activityIntent;
        if (forcechooser) {
            if (useNewStack)
                applyNewDocFlag(chooserIntent);
            activityIntent = Intent.createChooser(chooserIntent, c.getString(R.string.openwith));
        } else {
            activityIntent = chooserIntent;
            if (useNewStack)
                applyNewDocFlag(chooserIntent);
        }

        try {
            c.startActivity(activityIntent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c, useNewStack);
        }
    } else {
        openWith(f, c, useNewStack);
    }
}

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  ww  w  .  j  a va 2 s.c  om*/
}

From source file:com.krayzk9s.imgurholo.services.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    final NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    ids = intent.getParcelableArrayListExtra("ids");
    albumName = "/";
    downloaded = 0;//  ww w  .  j a  v a  2  s.c  o  m
    if (ids.size() > 0) {
        albumName += intent.getStringExtra("albumName") + "/";
        File myDirectory = new File(
                android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                albumName);
        if (!myDirectory.exists()) {
            myDirectory.mkdirs();
        }
    }
    for (int i = 0; i < ids.size(); i++) {
        try {
            final String type = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE)
                    .split("/")[1];
            final String id = ids.get(i).getJSONObject().getString("id");
            final String link = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK);
            Log.d("data", ids.get(i).getJSONObject().toString());
            Log.d(ImgurHoloActivity.IMAGE_DATA_TYPE,
                    ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE).split("/")[1]);
            Log.d("id", ids.get(i).getJSONObject().getString("id"));
            Log.d(ImgurHoloActivity.IMAGE_DATA_LINK,
                    ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK));
            final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
            notificationBuilder.setContentTitle(getString(R.string.picture_download))
                    .setContentText(getString(R.string.download_in_progress))
                    .setSmallIcon(R.drawable.icon_desaturated);
            Ion.with(getApplicationContext(), link).progress(new ProgressCallback() {
                @Override
                public void onProgress(int i, int i2) {
                    notificationBuilder.setProgress(i2, i, false);
                }
            }).write(new File(
                    android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                            + albumName + id + "." + type))
                    .setCallback(new FutureCallback<File>() {
                        @Override
                        public void onCompleted(Exception e, File file) {
                            if (file == null)
                                return;
                            downloaded += 1;
                            if (downloaded == ids.size()) {
                                NotificationCompat.Builder notificationComplete = new NotificationCompat.Builder(
                                        getApplicationContext());
                                if (ids.size() == 1) {
                                    Intent viewImageIntent = new Intent(Intent.ACTION_VIEW);
                                    viewImageIntent.setDataAndType(Uri.fromFile(file), "image/*");
                                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                                    shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                                    shareIntent.setType("image/*");
                                    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                                    PendingIntent viewImagePendingIntent = PendingIntent.getActivity(
                                            getApplicationContext(), (int) System.currentTimeMillis(),
                                            viewImageIntent, 0);
                                    PendingIntent sharePendingIntent = PendingIntent.getActivity(
                                            getApplicationContext(), (int) System.currentTimeMillis(),
                                            shareIntent, 0);
                                    notificationComplete.setContentTitle(getString(R.string.download_complete))
                                            .setSmallIcon(R.drawable.icon_desaturated)
                                            .setContentText(String.format(getString(R.string.download_progress),
                                                    downloaded))
                                            .setContentIntent(viewImagePendingIntent)
                                            .addAction(R.drawable.dark_social_share, getString(R.string.share),
                                                    sharePendingIntent);
                                } else {
                                    Intent i = new Intent(Intent.ACTION_PICK);
                                    i.setDataAndType(
                                            Uri.fromFile(new File(
                                                    android.os.Environment.getExternalStoragePublicDirectory(
                                                            Environment.DIRECTORY_PICTURES) + albumName)),
                                            "image/*");
                                    PendingIntent viewImagePendingIntent = PendingIntent.getActivity(
                                            getApplicationContext(), (int) System.currentTimeMillis(), i, 0);
                                    notificationComplete.setContentTitle(getString(R.string.download_complete))
                                            .setSmallIcon(R.drawable.icon_desaturated).setContentText(String
                                                    .format(getString(R.string.download_progress), downloaded))
                                            .setContentIntent(viewImagePendingIntent);
                                }
                                notificationManager.cancel(0);
                                notificationManager.cancel(1);
                                notificationManager.notify(1, notificationComplete.build());
                            }
                            MediaScannerConnection.scanFile(getApplicationContext(),
                                    new String[] { android.os.Environment.getExternalStoragePublicDirectory(
                                            Environment.DIRECTORY_PICTURES) + albumName + id + "." + type },
                                    null, new MediaScannerConnection.OnScanCompletedListener() {
                                        @Override
                                        public void onScanCompleted(final String path, final Uri uri) {
                                            Log.i("Scanning", String.format("Scanned path %s -> URI = %s", path,
                                                    uri.toString()));
                                        }
                                    });
                        }
                    });
            notificationManager.notify(0, notificationBuilder.build());
        } catch (JSONException e) {
            Log.e("Error!", e.toString());
        }
    }
}

From source file:com.github.snowdream.android.apps.imageviewer.ImageViewerActivity.java

public void doSettings() {
    if (!TextUtils.isEmpty(imageUri)) {
        Uri uri = Uri.parse(imageUri);/*from  w  ww  .ja va2 s.  c o  m*/
        Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
        intent.setDataAndType(uri, "image/jpg");
        intent.putExtra("mimeType", "image/jpg");
        startActivityForResult(Intent.createChooser(intent, getText(R.string.action_settings)), 200);
    }
}

From source file:com.amaze.filemanager.utils.files.FileUtils.java

public static void openWith(final DocumentFile f, final Context c, final boolean useNewStack) {
    MaterialDialog.Builder a = new MaterialDialog.Builder(c);
    a.title(c.getString(R.string.openas));
    String[] items = new String[] { c.getString(R.string.text), c.getString(R.string.image),
            c.getString(R.string.video), c.getString(R.string.audio), c.getString(R.string.database),
            c.getString(R.string.other) };

    a.items(items).itemsCallback((materialDialog, view, i, charSequence) -> {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        switch (i) {
        case 0://  ww  w .  ja  va 2  s . c o m
            if (useNewStack)
                applyNewDocFlag(intent);
            intent.setDataAndType(f.getUri(), "text/*");
            break;
        case 1:
            intent.setDataAndType(f.getUri(), "image/*");
            break;
        case 2:
            intent.setDataAndType(f.getUri(), "video/*");
            break;
        case 3:
            intent.setDataAndType(f.getUri(), "audio/*");
            break;
        case 4:
            intent = new Intent(c, DatabaseViewerActivity.class);
            intent.putExtra("path", f.getUri());
            break;
        case 5:
            intent.setDataAndType(f.getUri(), "*/*");
            break;
        }
        try {
            c.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c, useNewStack);
        }
    });

    a.build().show();
}

From source file:com.proofhq.Open.java

/**
 * Creates an intent for the data of mime type
 *
 * @param path/*  w  w  w  .j  a v a2 s  .  c o  m*/
 * @param callbackContext
 */
private void chooseIntent(String path, CallbackContext callbackContext) {
    if (path != null && path.length() > 0) {
        try {
            Uri uri = Uri.parse(path);
            String mime = getMimeType(path);
            Intent fileIntent = new Intent(Intent.ACTION_VIEW);

            if (Build.VERSION.SDK_INT > 15) {
                fileIntent.setDataAndTypeAndNormalize(uri, mime); // API Level 16 -> Android 4.1
            } else {
                fileIntent.setDataAndType(uri, mime);
            }

            cordova.getActivity().startActivity(fileIntent);

            callbackContext.success();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            callbackContext.error(1);
        }
    } else {
        callbackContext.error(2);
    }
}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public static void openunknown(File f, Context c, boolean forcechooser) {
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);

    String type = MimeTypes.getMimeType(f);
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        Uri uri = fileToContentUri(c, f);
        if (uri == null)
            uri = Uri.fromFile(f);/*ww w  . j  a  v  a2  s  .  c  om*/
        intent.setDataAndType(uri, type);
        Intent startintent;
        if (forcechooser)
            startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else
            startintent = intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c);
        }
    } else {
        openWith(f, c);
    }

}

From source file:activity.DetailsActivity.java

/**
 * Opens the document if it is on storage, else downloads it before open it.
 * // w ww  .  jav a2s  .c om
 * @param item
 *            the document to open
 */
public void openFileInMemory(final Document item) {
    mItem = item;
    MimeTypeMap map = MimeTypeMap.getSingleton();
    final String mime = map.getMimeTypeFromExtension(item.getExtension());
    mSubPath = item.getTitle() + "." + item.getExtension();

    if (mime != null) {
        if (item.isOnMemory() && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.fromFile(
                    new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            .getAbsolutePath() + "/" + mSubPath)),
                    mime.toLowerCase(Locale.US));

            startActivity(Intent.createChooser(i, getString(R.string.dialog_choose_app)));

        } else {
            getService().getDownloadTokenizedUrl(item.getList().getCours().getSysCode(),
                    item.getResourceString(), mDwlManagerHandler);
        }

    } else {
        DetailsActivity.this.getService().getDownloadTokenizedUrl(item.getList().getCours().getSysCode(),
                item.getResourceString(), mTokenizedURLHandler);
    }
}