Skip to content

Instantly share code, notes, and snippets.

@Razeeman
Last active January 30, 2019 17:52
Show Gist options
  • Save Razeeman/38c241b92b37cd838d85eebff8c08b61 to your computer and use it in GitHub Desktop.
Save Razeeman/38c241b92b37cd838d85eebff8c08b61 to your computer and use it in GitHub Desktop.
Android, Java, Implicit intents, Open webpage, Open map, Share text.
/**
* This method fires off an implicit Intent to open a webpage.
*
* @param url Url of webpage to open. Should start with http:// or https:// as that is the
* scheme of the URI expected with this Intent according to the Common Intents page
*/
private void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
/*
* This is a check we perform with every implicit Intent that we launch. In some cases,
* the device where this code is running might not have an Activity to perform the action
* with the data we've specified. Without this check, in those cases your app would crash.
*/
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d(TAG, "Couldn't call " + webpage.toString()
+ ", no receiving apps installed!");
}
}
/**
* This method will fire off an implicit Intent to view a location on a map.
*
* When constructing implicit Intents, you can use either the setData method or specify the
* URI as the second parameter of the Intent's constructor.
*
* @param addressString The string representing the location that will be opened in the map
*/
private void showMap(String addressString) {
Uri.Builder builder = new Uri.Builder();
builder.scheme("geo").appendQueryParameter("q", addressString);
Uri addressUri = builder.build();
// Uri addressUri = Uri.parse("geo:0,0?q=" + addressString);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(addressUri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d(TAG, "Couldn't call " + addressUri.toString()
+ ", no receiving apps installed!");
}
}
/**
* This method shares text and allows the user to select which app they would like to use to
* share the text. The chooser that is started using the {@link IntentBuilder#startChooser()}
* method will create a chooser when more than one app on the device can handle the Intent.
* If only one Activity on the phone can handle the Intent, it will automatically be launched.
*
* @param textToShare Text that will be shared
*/
private void shareText(String textToShare) {
ShareCompat.IntentBuilder
.from(this)
.setType("text/plain")
.setChooserTitle("Learning How to Share")
.setText(textToShare)
.startChooser();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment