Skip to content

Commit

Permalink
feat(android): add ability to share both text and file (#3233)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikosdouvlis authored Jul 9, 2020
1 parent 6196907 commit 4e8b59e
Showing 1 changed file with 26 additions and 16 deletions.
42 changes: 26 additions & 16 deletions android/capacitor/src/main/java/com/getcapacitor/plugin/Share.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,27 +27,29 @@ public void share(PluginCall call) {
call.error("Must provide a URL or Message");
return;
}

if(url != null && !isFileUrl(url) && !isHttpUrl(url)) {
call.error("Unsupported url");
return;
}

Intent intent = new Intent(Intent.ACTION_SEND);

if (text != null) {
// If they supplied both fields, concat em
if (url != null && url.startsWith("http")) {
text = text + " " + url;
}
if (url != null && isHttpUrl(url)) text = text + " " + url;
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.setTypeAndNormalize("text/plain");
} else if (url != null) {
if (url.startsWith("http")) {
intent.putExtra(Intent.EXTRA_TEXT, url);
intent.setTypeAndNormalize("text/plain");
} else if (url.startsWith("file:")) {
String type = getMimeType(url);
intent.setType(type);
Uri fileUrl = FileProvider.getUriForFile(getActivity(), getContext().getPackageName() + ".fileprovider", new File(Uri.parse(url).getPath()));
intent.putExtra(Intent.EXTRA_STREAM, fileUrl);
} else {
call.error("Unsupported url");
return;
}
}

if(url != null && isHttpUrl(url) && text == null) {
intent.putExtra(Intent.EXTRA_TEXT, url);
intent.setTypeAndNormalize("text/plain");
} else if (url != null && isFileUrl(url)) {
String type = getMimeType(url);
intent.setType(type);
Uri fileUrl = FileProvider.getUriForFile(getActivity(), getContext().getPackageName() + ".fileprovider", new File(Uri.parse(url).getPath()));
intent.putExtra(Intent.EXTRA_STREAM, fileUrl);
}

if (title != null) {
Expand All @@ -69,4 +71,12 @@ private String getMimeType(String url) {
}
return type;
}

private boolean isFileUrl(String url) {
return url.startsWith("file:");
}

private boolean isHttpUrl(String url) {
return url.startsWith("http");
}
}

0 comments on commit 4e8b59e

Please sign in to comment.