↓ This thing
I felt that there was a lot of information, but it didn't come out unexpectedly, so I wrote a memo.
SomeActivity.java
//Prerequisite code to run from within the activity
private void showShareChooser() {
File tempFile = new File(getApplicationContext().getExternalCacheDir(), tempImgFilePath);
//If you want to get the URI to share the file, you need to get it by specifying the name of the authority described later through FileProvider.
Uri uri = FileProvider.getUriForFile(getApplicationContext()
, getApplicationContext().getPackageName() + ".provider"
, tempFile);
ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(this);
builder.setChooserTitle(chooserTitle) //Title when sharing
.setSubject(subject) //subject. How it is used depends on the shared app
.setText(text) //Text. How it is used depends on the shared app
.setStream(uri) //When sharing a file, specify its URI
.setType("image/jpeg"); //MIME type of the file specified in the stream
//Grant read permission on the URI
Intent intent = builder.createChooserIntent().addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//If you want to receive a callback, use that intent to start the activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, SNS_SHARE);
}
//If you don't need to receive the results, you can just start from the builder
// builder.startChooser();
}
If you want to receive the return, you can receive it with ʻonActivityResult` as usual.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SNS_SHARE:
//Receive the return and do something
//resultCode is always zero, so RESULT_Do not judge with OK
doSomething();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
When sharing images etc., Bitmap cannot be shared as it is, so it is necessary to save it to a file once. In addition, it is necessary to allow reading from the save destination as follows.
First, specify the path in XML.
src/main/res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path name="cache" path="." />
</paths>
ʻExternal-cache-path etc. changes depending on the save destination. Although it is in English, see [Official FileProvider Reference](https://developer.android.com/reference/android/support/v4/content/FileProvider). Then specify that provider in ʻAndroidManifest.xml
.
AndroidManifest.xml
<manifest
package="com.example"
xmlns:android="http://schemas.android.com/apk/res/android">
:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
:
</application>
:
</manifest>
Recommended Posts