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.zia.freshdocs.widget.adapter.CMISAdapter.java

/**
 * Send an Intent requesting for an activity to display the content.
 * //from   w  w  w .j  a  v  a  2s  .co m
 * @param file
 * @param ref
 */
protected void viewContent(File file, NodeRef ref) {
    Context context = getContext();

    // Ask for viewer
    Uri uri = Uri.fromFile(file);
    Intent viewIntent = new Intent(Intent.ACTION_VIEW);
    viewIntent.setDataAndType(uri, ref.getContentType());
    try {
        context.startActivity(viewIntent);
    } catch (ActivityNotFoundException e) {
        deleteContent(file);
        String text = "No viewer found for " + ref.getContentType();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

From source file:com.flyingcrop.ScreenCaptureFragment.java

void notifySS(Bitmap bitmap, String date, String dir) {

    File file = new File(dir);

    if (file.exists()) {
        Log.d("FlyingCrop", "O ficheiro a ser partilhado existe");
    } else {// w w w  . j a  v  a  2s  . c  o m
        Log.d("FlyingCrop", "O ficheiro a ser partilhado no existe");
    }

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/png");
    share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));

    PendingIntent i = PendingIntent.getActivity(getActivity(), 0,
            Intent.createChooser(share, getResources().getString(R.string.fragment_share)),
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "image/png");
    PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notif = new Notification.Builder(getActivity()).setContentTitle(date + ".png")
            .setContentText(getResources().getString(R.string.fragment_img_preview))
            .addAction(android.R.drawable.ic_menu_share, getResources().getString(R.string.fragment_share), i)
            .setSmallIcon(com.flyingcrop.R.drawable.ab_ico).setLargeIcon(bitmap)
            .setStyle(new Notification.BigPictureStyle().bigPicture(bitmap)).setContentIntent(pendingIntent)
            .setPriority(Notification.PRIORITY_MAX)

            .build();
    final SharedPreferences settings = getActivity().getSharedPreferences("data", 0);

    NotificationManager notificationManager = (NotificationManager) getActivity()
            .getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, notif);

    if (settings.getBoolean("vibration", false)) {
        Vibrator v = (Vibrator) this.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(100);
    }
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

private Intent buildIntent(String action, String uri, String type, JSONObject extras, String packagename,
        String classname, JSONArray categories) throws JSONException {
    Intent intent = new Intent(action);
    intent.setDataAndType(uri != null ? Uri.parse(uri) : null, type);
    if (packagename != null && classname != null) {
        intent.setComponent(new ComponentName(packagename, classname));
    }//from  www.jav  a  2  s . c o  m
    if (extras != null) {
        putExtrasFromJsonObject(extras, intent);
    }
    if (categories != null) {
        for (int i = 0; i < categories.length(); i++) {
            intent.addCategory(categories.getString(i));
        }
    }
    return intent;
}

From source file:com.android.messaging.ui.UIIntentsImpl.java

@Override
public void launchFullScreenVideoViewer(final Context context, final Uri videoUri) {
    final Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    // So we don't see "surrounding" images in Gallery
    intent.putExtra("SingleItemOnly", true);
    intent.setDataAndType(videoUri, ContentType.VIDEO_UNSPECIFIED);
    startExternalActivity(context, intent);
}

From source file:de.sitewaerts.cordova.documentviewer.DocumentViewerPlugin.java

private void _open(String url, String contentType, String packageId, String activity,
        CallbackContext callbackContext, Bundle viewerOptions) throws JSONException {
    clearTempFiles();/*from  w ww.  java  2  s  .  c o m*/

    File file = getAccessibleFile(url);

    if (file != null && file.exists() && file.isFile()) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri path = Uri.fromFile(file);

            // @see http://stackoverflow.com/questions/2780102/open-another-application-from-your-own-intent
            intent.addCategory(Intent.CATEGORY_EMBED);
            intent.setDataAndType(path, contentType);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(this.getClass().getName(), viewerOptions);
            //activity needs fully qualified name here
            intent.setComponent(new ComponentName(packageId, packageId + "." + activity));

            this.callbackContext = callbackContext;
            this.cordova.startActivityForResult(this, intent, REQUEST_CODE_OPEN);

            // send shown event
            JSONObject successObj = new JSONObject();
            successObj.put(Result.STATUS, PluginResult.Status.OK.ordinal());
            PluginResult result = new PluginResult(PluginResult.Status.OK, successObj);
            // need to keep callback for close event
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put(Result.STATUS, PluginResult.Status.ERROR.ordinal());
            errorObj.put(Result.MESSAGE, "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put(Result.STATUS, PluginResult.Status.ERROR.ordinal());
        errorObj.put(Result.MESSAGE, "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:com.android.music.PlaylistBrowserFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.media_picker_activity, null);

    final Intent intent = getActivity().getIntent();
    final String action = intent.getAction();
    if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
        mCreateShortcut = true;//ww w  .  j  a  va  2  s .com
    }

    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    mToken = MusicUtils.bindToService(getActivity(), new ServiceConnection() {
        public void onServiceConnected(ComponentName classname, IBinder obj) {
            if (Intent.ACTION_VIEW.equals(action)) {
                Bundle b = intent.getExtras();
                if (b == null) {
                    Log.w(TAG, "Unexpected:getExtras() returns null.");
                } else {
                    try {
                        long id = Long.parseLong(b.getString("playlist"));
                        if (id == RECENTLY_ADDED_PLAYLIST) {
                            playRecentlyAdded();
                        } else if (id == PODCASTS_PLAYLIST) {
                            playPodcasts();
                        } else if (id == ALL_SONGS_PLAYLIST) {
                            long[] list = MusicUtils.getAllSongs(getActivity());
                            if (list != null) {
                                MusicUtils.playAll(getActivity(), list, 0);
                            }
                        } else {
                            MusicUtils.playPlaylist(getActivity(), id);
                        }
                    } catch (NumberFormatException e) {
                        Log.w(TAG, "Playlist id missing or broken");
                    }
                }
                getActivity().finish();
                return;
            }
            MusicUtils.updateNowPlaying(getActivity());
        }

        public void onServiceDisconnected(ComponentName classname) {
        }

    });

    IntentFilter f = new IntentFilter();
    f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
    f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
    f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    f.addDataScheme("file");
    getActivity().registerReceiver(mScanListener, f);

    lv = (ListView) view.findViewById(android.R.id.list);
    lv.setOnCreateContextMenuListener(this);
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mCreateShortcut) {
                final Intent shortcut = new Intent();
                shortcut.setAction(Intent.ACTION_VIEW);
                shortcut.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/playlist");
                shortcut.putExtra("playlist", String.valueOf(id));

                final Intent intent = new Intent();
                intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
                intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                        ((TextView) view.findViewById(R.id.line1)).getText());
                intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                        .fromContext(getActivity(), R.drawable.ic_launcher_shortcut_music_playlist));

                getActivity().setResult(getActivity().RESULT_OK, intent);
                getActivity().finish();
                return;
            }
            if (id == RECENTLY_ADDED_PLAYLIST) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
                intent.putExtra("playlist", "recentlyadded");
                startActivity(intent);
            } else if (id == PODCASTS_PLAYLIST) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
                intent.putExtra("playlist", "podcasts");
                startActivity(intent);
            } else {
                Intent intent = new Intent(Intent.ACTION_EDIT);
                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
                intent.putExtra("playlist", Long.valueOf(id).toString());
                startActivity(intent);
            }

        }
    });

    mAdapter = (PlaylistListAdapter) getActivity().getLastNonConfigurationInstance();
    if (mAdapter == null) {
        //Log.i("@@@", "starting query");
        mAdapter = new PlaylistListAdapter(getActivity().getApplication(), this, R.layout.track_list_item,
                mPlaylistCursor, new String[] { MediaStore.Audio.Playlists.NAME },
                new int[] { android.R.id.text1 });
        lv.setAdapter(mAdapter);
        //setTitle(R.string.working_playlists);
        getPlaylistCursor(mAdapter.getQueryHandler(), null);
    } else {
        mAdapter.setActivity(this);
        lv.setAdapter(mAdapter);
        mPlaylistCursor = mAdapter.getCursor();
        // If mPlaylistCursor is null, this can be because it doesn't have
        // a cursor yet (because the initial query that sets its cursor
        // is still in progress), or because the query failed.
        // In order to not flash the error dialog at the user for the
        // first case, simply retry the query when the cursor is null.
        // Worst case, we end up doing the same query twice.
        if (mPlaylistCursor != null) {
            init(mPlaylistCursor);
        } else {
            //setTitle(R.string.working_playlists);
            getPlaylistCursor(mAdapter.getQueryHandler(), null);
        }
    }

    return view;
}

From source file:com.app.sample.chatting.activity.chat.ChatActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == TAKE_PICTURE) {
        if (resultCode != Activity.RESULT_OK) {
            //TODO ????

            File bb = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "temp.jpg");

            Intent i = new Intent("com.android.camera.action.CROP");
            i.setType("image/*");

            //i.putExtra("data", bb);// ww w  . j  av a 2  s . c  om
            i.setDataAndType(Uri.fromFile(bb), "image/jpeg");

            i.putExtra("crop", "true");

            i.putExtra("aspectX", 1);

            i.putExtra("aspectY", 1);

            i.putExtra("outputX", 500);

            i.putExtra("outputY", 500);

            i.putExtra("return-data", true);

            this.startActivityForResult(i, 7);

            /*if (data != null) {
            //??
                    
            if (data.hasExtra("data")) {
                Bitmap tempPic = data.getParcelableExtra("data");
                ivTakedPic.setVisibility(View.VISIBLE);
                ivTakedPic.setImageBitmap(tempPic);
            } else {
                //?Uri
                int width = ivTakedPic.getWidth();
                int height = ivTakedPic.getHeight();
                BitmapFactory.Options factoryOption = new BitmapFactory.Options();
                factoryOption.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(outputFileUri.getPath(),factoryOption);
                int imageWidth = factoryOption.outWidth;
                int imageHeight = factoryOption.outHeight;
                //?
                int scaleFactor = Math.min(imageWidth/width,imageHeight/height);
                //????
                factoryOption.inJustDecodeBounds = false;
                factoryOption.inSampleSize = scaleFactor;
                factoryOption.inPurgeable = true;
                    
                Bitmap bitmap = BitmapFactory.decodeFile(outputFileUri.getPath(),factoryOption);
                ivTakedPic.setImageBitmap(bitmap);
            }
            }*/
            return;
        }
    }
    if (requestCode == REQUEST_CODE_GETIMAGE_BYSDCARD) {
        Uri dataUri = data.getData();
        if (dataUri != null) {
            File file = FileUtils.uri2File(aty, dataUri);
            MessageChat message = new MessageChat(MessageChat.MSG_TYPE_PHOTO, MessageChat.MSG_STATE_SUCCESS,
                    "Tom", "avatar", "Jerry", "avatar", file.getAbsolutePath(), true, true, new Date());
            datas.add(message);
            adapter.refresh(datas);
        }
    }
}

From source file:com.lastsoft.plog.adapter.GameAdapter.java

public void playPopup(View v, final int position) {

    try {/*w ww  .  j  a v a2  s.  c  om*/
        InputMethodManager inputManager = (InputMethodManager) mActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception ignored) {
    }

    PopupMenu popup = new PopupMenu(mActivity, v);

    MenuInflater inflater = popup.getMenuInflater();

    if (games.get(position).expansionFlag == true) {
        inflater.inflate(R.menu.game_expansion_overflow, popup.getMenu());
    } else {
        inflater.inflate(R.menu.game_overflow, popup.getMenu());
    }
    if (games.get(position).gameBGGID == null || games.get(position).gameBGGID.equals("")) {
        popup.getMenu().removeItem(R.id.update_bgg);
        popup.getMenu().removeItem(R.id.open_bgg);
        popup.getMenu().removeItem(R.id.add_bgg);
    }
    if (games.get(position).gameBoxImage == null || games.get(position).gameBoxImage.equals("")) {
        popup.getMenu().removeItem(R.id.view_box_photo);
    }
    if (games.get(position).taggedToPlay <= 0) {
        popup.getMenu().removeItem(R.id.remove_bucket_list);
    } else {
        popup.getMenu().removeItem(R.id.add_bucket_list);
    }

    SharedPreferences app_preferences;
    app_preferences = PreferenceManager.getDefaultSharedPreferences(mActivity);
    long currentDefaultPlayer = app_preferences.getLong("defaultPlayer", -1);
    if (games.get(position).collectionFlag || currentDefaultPlayer == -1) {
        popup.getMenu().removeItem(R.id.add_bgg);
    }

    //check if this game has been played
    //if so, can't delete
    if (GamesPerPlay.hasGameBeenPlayed(games.get(position))) {
        popup.getMenu().removeItem(R.id.delete_game);
    }
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.delete_game:
                ((MainActivity) mActivity).deleteGame(games.get(position).getId());
                return true;
            case R.id.add_tenbyten:
                ((MainActivity) mActivity).addToTenXTen(games.get(position).getId());
                return true;
            case R.id.view_plays:
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 9, fragmentName,
                            currentYear);
                } else {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 0, fragmentName,
                            currentYear);
                }
                return true;
            case R.id.open_bgg:
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://bgg.cc/boardgame/" + games.get(position).gameBGGID));
                mActivity.startActivity(browserIntent);
                return true;
            case R.id.update_bgg:
                mPosition = position;
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, true, -1);
                } else {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, false, -1);
                }
                return true;
            case R.id.add_bgg:
                mPosition = position;
                ((MainActivity) mActivity).updateGameViaBGG(games.get(position).gameName,
                        games.get(position).gameBGGID, "", true, false);
                return true;
            case R.id.add_box_photo:
                ((GamesFragment) mFragment).captureBox(games.get(position));
                return true;
            case R.id.view_box_photo:
                String[] photoParts = games.get(position).gameBoxImage.split("/");
                File newFile = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                                + "/Plog/",
                        photoParts[photoParts.length - 1]);
                Uri contentUri = FileProvider.getUriForFile(mActivity.getApplicationContext(),
                        "com.lastsoft.plog.fileprovider", newFile);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(contentUri, "image/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                mActivity.startActivity(intent);
                return true;
            case R.id.add_bucket_list:
                String[] ids = TimeZone.getAvailableIDs(-5 * 60 * 60 * 1000);
                // if no ids were returned, something is wrong. get out.
                //if (ids.length == 0)
                //    System.exit(0);

                // begin output
                //System.out.println("Current Time");

                // create a Eastern Standard Time time zone
                SimpleTimeZone pdt = new SimpleTimeZone(-5 * 60 * 60 * 1000, ids[0]);

                // set up rules for daylight savings time
                pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
                pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

                // create a GregorianCalendar with the Pacific Daylight time zone
                // and the current date and time
                Calendar calendar = new GregorianCalendar(pdt);
                Date trialTime = new Date();
                calendar.setTime(trialTime);
                int i = (int) (calendar.getTime().getTime() / 1000);
                games.get(position).taggedToPlay = i;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.added_to_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                games.get(position).taggedToPlay = 0;
                                games.get(position).save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!

                return true;
            case R.id.remove_bucket_list:
                final int taggedToPlay = games.get(position).taggedToPlay;
                final Game gameToUndo = games.get(position);
                games.get(position).taggedToPlay = 0;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.removed_from_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                gameToUndo.taggedToPlay = taggedToPlay;
                                gameToUndo.save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!
                if (playListType == 2) {
                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                }
                return true;
            default:
                return false;
            }
        }
    }

    );
    popup.show();
}

From source file:br.com.GUI.avaliacoes.AvaliarPerimetria.java

private void cortar(int requestCode) {
     try {// ww  w.ja va2s  . c o m
         //call the standard crop action intent (the user device may not support it)
         Intent cropIntent = new Intent("com.android.camera.action.CROP");
         //indicate image type and Uri
         cropIntent.setDataAndType(selectedImageUri, "image/*");
         //set crop properties
         cropIntent.putExtra("crop", "true");
         //indicate aspect of desired crop
         cropIntent.putExtra("aspectX", 1);
         cropIntent.putExtra("aspectY", 1);
         //indicate output X and Y
         cropIntent.putExtra("outputX", 256);
         cropIntent.putExtra("outputY", 256);
         //retrieve data on return
         cropIntent.putExtra("return-data", true);
         //start the activity - we handle returning in onActivityResult
         startActivityForResult(cropIntent, requestCode + 2);
     }
     //respond to users whose devices do not support the crop action
     catch (ActivityNotFoundException anfe) {
         //display an error message
         String errorMessage = "Whoops - your device doesn't support the crop action!";
         Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
         toast.show();
     }
 }

From source file:com.amaze.filemanager.fragments.MainFragment.java

public static void launchSMB(final HybridFileParcelable baseFile, final Activity activity) {
    final Streamer s = Streamer.getInstance();
    new Thread() {
        public void run() {
            try {
                /*//from   w  w  w.  j av  a 2  s. c om
                List<SmbFile> subtitleFiles = new ArrayList<SmbFile>();
                        
                // finding subtitles
                for (Layoutelements layoutelement : LIST_ELEMENTS) {
                SmbFile smbFile = new SmbFile(layoutelement.getDesc());
                if (smbFile.getName().contains(smbFile.getName())) subtitleFiles.add(smbFile);
                }
                */

                s.setStreamSrc(new SmbFile(baseFile.getPath()), baseFile.getSize());
                activity.runOnUiThread(() -> {
                    try {
                        Uri uri = Uri.parse(Streamer.URL + Uri
                                .fromFile(new File(Uri.parse(baseFile.getPath()).getPath())).getEncodedPath());
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setDataAndType(uri,
                                MimeTypes.getMimeType(baseFile.getPath(), baseFile.isDirectory()));
                        PackageManager packageManager = activity.getPackageManager();
                        List<ResolveInfo> resInfos = packageManager.queryIntentActivities(i, 0);
                        if (resInfos != null && resInfos.size() > 0)
                            activity.startActivity(i);
                        else
                            Toast.makeText(activity,
                                    activity.getResources().getString(R.string.smb_launch_error),
                                    Toast.LENGTH_SHORT).show();
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                });

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