Skip to content

Instantly share code, notes, and snippets.

@hkosacki
Created March 1, 2017 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkosacki/176cc27d50e5c75e7d4bdd70cb70f95e to your computer and use it in GitHub Desktop.
Save hkosacki/176cc27d50e5c75e7d4bdd70cb70f95e to your computer and use it in GitHub Desktop.
private void handleDropEvent(View view, DragEvent dragEvent) {
ClipData clipData = dragEvent.getClipData();
ClipData.Item item = clipData.getItemAt(0);
Uri uri = item.getUri();
if (uri != null) {
String mimeType = URLConnection.guessContentTypeFromName(new File(uri.getPath()).getName());
if (mimeType == null) {
Snackbar.make(mainLayout, "Can't open file. The file type is unknown.", Snackbar.LENGTH_LONG).show();
} else if (mimeType.startsWith("image")) {
handleImage(uri);
} else {
Intent newIntent = new Intent(Intent.ACTION_VIEW);
Uri contentUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", new File(uri.getPath()));
newIntent.setDataAndType(contentUri, mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(newIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
try {
startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Snackbar.make(mainLayout, "Sorry, I found no handler for this type of file.", Snackbar.LENGTH_SHORT).show();
} catch (FileUriExposedException ex) {
Snackbar.make(mainLayout, "FileUriExposedException", Snackbar.LENGTH_SHORT).show();
}
}
} else if (item.getText() != null) {
handleText(item.getText());
} else {
Log.e(TAG, "Unknown content: " + clipData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment