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:com.intervigil.micdroid.MainActivity.java

@Override
public void onPlay(Recording r) {
    Intent playIntent = new Intent(Intent.ACTION_VIEW);
    File privateRootDir = getFilesDir();
    File recordingFile = new File(privateRootDir, r.getName());
    playIntent.setDataAndType(Uri.fromFile(recordingFile), Constants.MIME_AUDIO_WAV);
    startActivity(playIntent);/*from  www.  j  av a2s.c  om*/
}

From source file:io.github.pwlin.cordova.plugins.fileopener2.FileOpener2.java

private void _open(String fileArg, String contentType, CallbackContext callbackContext) throws JSONException {
    String fileName = "";
    try {/*from   www. j  ava2 s .  c  o  m*/
        CordovaResourceApi resourceApi = webView.getResourceApi();
        Uri fileUri = resourceApi.remapUri(Uri.parse(fileArg));
        fileName = this.stripFileProtocol(fileUri.toString());
    } catch (Exception e) {
        fileName = fileArg;
    }
    File file = new File(fileName);
    if (file.exists()) {
        try {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24) {

                Context context = cordova.getActivity().getApplicationContext();
                path = FileProvider.getUriForFile(context,
                        cordova.getActivity().getPackageName() + ".opener.provider", file);
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                List<ResolveInfo> infoList = context.getPackageManager().queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : infoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, path,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
            /*
             * @see
             * http://stackoverflow.com/questions/14321376/open-an-activity-from-a-cordovaplugin
             */
            cordova.getActivity().startActivity(intent);
            //cordova.getActivity().startActivity(Intent.createChooser(intent,"Open File in..."));
            callbackContext.success();
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put("status", PluginResult.Status.ERROR.ordinal());
            errorObj.put("message", "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put("status", PluginResult.Status.ERROR.ordinal());
        errorObj.put("message", "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:cm.aptoide.pt.RemoteInSearch.java

private void installApk(String apk_pkg, int position) {
    pkginfo = mPm.getPackageArchiveInfo(apk_pkg, 0); //variavel global usada no retorno da instalacao
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" + apk_pkg), "application/vnd.android.package-archive");

    Message msg = new Message();
    msg.arg1 = 1;/*from   w w  w . j  a v  a  2s.  c  o m*/
    download_handler.sendMessage(msg);

    startActivityForResult(intent, position);
}

From source file:com.andrew.apolloMod.activities.QueryBrowserActivity.java

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    if (mAdapter != null) {
        getQueryCursor(mAdapter.getQueryHandler(), null);
    }// w w  w .java2  s.c  o  m

    Intent intent = getIntent();
    String action = intent != null ? intent.getAction() : null;

    if (Intent.ACTION_VIEW.equals(action)) {
        // this is something we got from the search bar
        Uri uri = intent.getData();
        String path = uri.toString();
        if (path.startsWith("content://media/external/audio/media/")) {
            // This is a specific file
            String id = uri.getLastPathSegment();
            long[] list = new long[] { Long.valueOf(id) };
            MusicUtils.playAll(this, list, 0);
            finish();
            return;
        } else if (path.startsWith("content://media/external/audio/albums/")) {
            // This is an album, show the songs on it
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
            i.putExtra("album", uri.getLastPathSegment());
            startActivity(i);
            finish();
            return;
        } else if (path.startsWith("content://media/external/audio/artists/")) {
            intent = new Intent(Intent.ACTION_VIEW);

            Bundle bundle = new Bundle();
            bundle.putString(MIME_TYPE, Audio.Artists.CONTENT_TYPE);
            bundle.putString(ARTIST_KEY, uri.getLastPathSegment());
            bundle.putLong(BaseColumns._ID, ApolloUtils.getArtistId(uri.getLastPathSegment(), ARTIST_ID, this));

            intent.setClass(this, TracksBrowser.class);
            intent.putExtras(bundle);
            startActivity(intent);
            return;
        }
    }

    mFilterString = intent.getStringExtra(SearchManager.QUERY);
    if (MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)) {
        String focus = intent.getStringExtra(MediaStore.EXTRA_MEDIA_FOCUS);
        String artist = intent.getStringExtra(MediaStore.EXTRA_MEDIA_ARTIST);
        String album = intent.getStringExtra(MediaStore.EXTRA_MEDIA_ALBUM);
        String title = intent.getStringExtra(MediaStore.EXTRA_MEDIA_TITLE);
        if (focus != null) {
            if (focus.startsWith("audio/") && title != null) {
                mFilterString = title;
            } else if (focus.equals(Audio.Albums.ENTRY_CONTENT_TYPE)) {
                if (album != null) {
                    mFilterString = album;
                    if (artist != null) {
                        mFilterString = mFilterString + " " + artist;
                    }
                }
            } else if (focus.equals(Audio.Artists.ENTRY_CONTENT_TYPE)) {
                if (artist != null) {
                    mFilterString = artist;
                }
            }
        }
    }

    setContentView(R.layout.listview);
    mTrackList = getListView();
    mTrackList.setTextFilterEnabled(true);
    if (mAdapter == null) {
        mAdapter = new QueryListAdapter(getApplication(), this, R.layout.listview_items, null, // cursor
                new String[] {}, new int[] {}, 0);
        setListAdapter(mAdapter);
        if (TextUtils.isEmpty(mFilterString)) {
            getQueryCursor(mAdapter.getQueryHandler(), null);
        } else {
            mTrackList.setFilterText(mFilterString);
            mFilterString = null;
        }
    } else {
        mAdapter.setActivity(this);
        setListAdapter(mAdapter);
        mQueryCursor = mAdapter.getCursor();
        if (mQueryCursor != null) {
            init(mQueryCursor);
        } else {
            getQueryCursor(mAdapter.getQueryHandler(), mFilterString);
        }
    }

    LinearLayout emptyness = (LinearLayout) findViewById(R.id.empty_view);
    emptyness.setVisibility(View.GONE);
}

From source file:com.CPTeam.VselCalc.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");
    if (update_file.length() > 0) {
        // raise notification
        Notification notification = new Notification(appIcon, appName + " update", System.currentTimeMillis());
        notification.flags |= NOTIFICATION_FLAGS;

        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Select to install";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);//from   ww  w .  ja v  a 2  s . c om
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        nm.notify(NOTIFICATION_ID, notification);
    } else {
        nm.cancel(NOTIFICATION_ID);
    }
}

From source file:abanoubm.dayra.main.Main.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == FOLDER_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.setDataAndType(Uri.fromFile(new File(Utility.getDayraFolder())), "*/*");
            startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
        }//from  ww w  . j a v  a2  s.co  m

    } else if (requestCode == IMPORT_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            importDB();

    }
}

From source file:com.hagreve.android.HaGreveDetailActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
    case android.R.id.home:
        // app icon in action bar clicked; go home
        intent = new Intent(this, HaGreveActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);/*from  w  ww .ja  v  a  2s  .co m*/
        return true;
    case R.id.detail_source_button:
        if (strike.getSourceUrl() != null) {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(strike.getSourceUrl()), "text/html");
            startActivity(intent);
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.android.mms.rcs.FavoriteDetailAdapter.java

private void showOpenRcsVcardDialog() {
    final String vcardFileName = mCursor
            .getString(mCursor.getColumnIndexOrThrow(FavoriteMessageProvider.FavoriteMessage.FILE_NAME));
    final String[] openVcardItems = new String[] { mContext.getString(R.string.vcard_detail_info),
            mContext.getString(R.string.vcard_import), mContext.getString(R.string.merge_contacts) };
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setItems(openVcardItems, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
            case SHOW_DETAIL_VCARD:
                ArrayList<PropertyNode> propList = RcsMessageOpenUtils.openRcsVcardDetail(mContext,
                        vcardFileName);/*from w w  w.java  2s  .  c  om*/
                RcsMessageOpenUtils.showDetailVcard(mContext, propList);
                break;
            case VIEW_VCARD_FROM_MMS:
                try {
                    File file = new File(vcardFileName);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), mContentType.toLowerCase());
                    intent.putExtra("VIEW_VCARD_FROM_MMS", true);
                    mContext.startActivity(intent);
                } catch (Exception e) {
                    RcsLog.w(e);
                }
                break;
            case MERGE_VCARD_DETAIL:
                ArrayList<PropertyNode> mergePropList = openRcsVcardDetail(mContext, vcardFileName);
                mergeVcardDetail(mContext, mergePropList);
                break;
            default:
                break;
            }
        }
    });
    builder.create().show();
}

From source file:com.first3.viz.ui.ActivityDelegate.java

public void play(Uri videoUri) {
    boolean useExternalPlayer = VizApp.getPrefs().getBoolean(Preferences.USE_EXTERNAL_PLAYER, false);

    if (useExternalPlayer) {
        Intent intent = new Intent(Intent.ACTION_VIEW, videoUri);
        intent.setDataAndType(videoUri, "video/*");
        startActivity(intent);//from   ww w  .j a va2s  .co  m
    } else {
        switchToVideoView();
        getVideoPlayerFragment().start(videoUri);
    }
}

From source file:com.phonegap.plugins.fileopener.FileOpener.java

private void openFile(String url) throws IOException {
    // Create URI
    Uri uri = Uri.parse(url);//from  www. ja  va  2 s.  c o  m

    Intent intent = null;
    // Check what kind of file you are trying to open, by comparing the url with extensions.
    // When the if condition is matched, plugin sets the correct intent (mime) type, 
    // so Android knew what application to use to open the file

    if (url.contains(".doc") || url.contains(".docx")) {
        // Word document
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/msword");
    } else if (url.contains(".pdf")) {
        // PDF file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/pdf");
    } else if (url.contains(".ppt") || url.contains(".pptx")) {
        // Powerpoint file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
    } else if (url.contains(".xls") || url.contains(".xlsx")) {
        // Excel file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.ms-excel");
    } else if (url.contains(".rtf")) {
        // RTF file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/rtf");
    } else if (url.contains(".wav")) {
        // WAV audio file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "audio/x-wav");
    } else if (url.contains(".gif")) {
        // GIF file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "image/gif");
    } else if (url.contains(".jpg") || url.contains(".jpeg")) {
        // JPG file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "image/jpeg");
    } else if (url.contains(".txt")) {
        // Text file
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "text/plain");
    } else if (url.contains(".mpg") || url.contains(".mpeg") || url.contains(".mpe") || url.contains(".mp4")
            || url.contains(".avi")) {
        // Video files
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    }

    //if you want you can also define the intent type for any other file

    //additionally use else clause below, to manage other unknown extensions
    //in this case, Android will show all applications installed on the device
    //so you can choose which application to use

    else {
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "*/*");
    }

    this.cordova.getActivity().startActivity(intent);
}