diff --git a/.gitignore b/.gitignore index 06de402..7936403 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,7 @@ proguard/ captures/ \.idea/ + +*.iml + +resource-file-provider/secrets\.properties diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..1b6c13d --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +language: android +env: + - BINTRAY_USER=xxxxUSERxxxx BINTRAY_APIKEY=xxxxAPIKEYxxxx +android: + components: + - platform-tools + - build-tools-28.0.3 + - android-28 + - extra-android-m2repository +before_script: +- mkdir "$ANDROID_HOME/licenses" || true +- echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" > "$ANDROID_HOME/licenses/android-sdk-license" +script: +- ./gradlew resource-file-provider:check +before_install: +- chmod +x gradlew \ No newline at end of file diff --git a/README.md b/README.md index 98b54fe..b4f363a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,113 @@ +# Android Resource File Provider + [![Build Status](https://travis-ci.org/federicoboschini/Android-Resource-File-Provider.svg?branch=master)](https://travis-ci.org/federicoboschini/Android-Resource-File-Provider) -Android Resource File Provider +Easily share audio, video, image and document files from `raw`, `assets` and `drawable` folders **without any specific permission**. + +## Installation + +Add the repository at the top of your app `build.gradle`: + +```groovy +repositories { + maven { + url "https://dl.bintray.com/boschini/android-libraries" + } +} +``` + +Include the dependency in your app `build.gradle` file: + +```groovy +implementation 'it.federicoboschini:resource-file-provider:1.0.0' +``` + +If you are experiencing any issue with resource merging or support-library compatibility add the dependency excluding `com.android.support`: + +```groovy +implementation('it.federicoboschini:resource-file-provider:1.0.0') { + exclude group: 'com.android.support' +} +``` + +## Configuration + +Add this to your app `AndroidManifest.xml`: + +```xml + + + + + + + +``` + +**Optional** Add this (provider authority) to your app `strings.xml`: + +```xml + + + it.my_company.my_app.my_authority + + +``` + +**Optional** Define custom file paths by creating a `file_provider_paths` in `res/xml`: + +```xml + + + + + + + + +``` + +## Example: share a mp3 file + +```java +try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_RAW) + .setFileName("my_sound") + .setFileExtension("mp3") + .setFileType(TYPE_AUDIO) + .build() + .shareFile(); +} catch (FileNotFoundException e) { + e.printStackTrace(); +} +``` + +***Note:*** `setFileName` parameter is **without** the extension. + +### Current supported and tested extensions: + +* `.mp3` +* `.jpg` +* `.png` +* `.pdf` +* `.mp4` + +### Current supported and tested folders: + +* `drawable` +* `raw` +* `assets` + +***Note:*** if your project contains density-dependent drawables, the nearest to the device density will be selected. + +### Known issues: + +* Can't get images from `mipmap` folder. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..06d67d7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.3.0' + classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' + + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + maven { + url "https://dl.bintray.com/boschini/android-libraries" + } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..743d692 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,13 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7a3265e Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..aafc5ba --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jan 22 22:09:02 CET 2019 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/resource-file-provider/.gitignore b/resource-file-provider/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/resource-file-provider/.gitignore @@ -0,0 +1 @@ +/build diff --git a/resource-file-provider/build.gradle b/resource-file-provider/build.gradle new file mode 100644 index 0000000..04239dc --- /dev/null +++ b/resource-file-provider/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'com.jfrog.bintray' version '1.7.3' + id 'com.novoda.build-properties' version '0.4.1' +} + +apply plugin: 'com.android.library' +apply plugin: 'com.jfrog.bintray' +apply plugin: 'com.github.dcendents.android-maven' +apply plugin: 'com.novoda.build-properties' +apply from: 'distribution.gradle' + +android { + compileSdkVersion 28 + + defaultConfig { + minSdkVersion 14 + targetSdkVersion 28 + versionCode 0 + versionName version + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + + api 'com.android.support:appcompat-v7:28.0.0' + + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' +} diff --git a/resource-file-provider/distribution.gradle b/resource-file-provider/distribution.gradle new file mode 100644 index 0000000..6092f19 --- /dev/null +++ b/resource-file-provider/distribution.gradle @@ -0,0 +1,74 @@ +buildProperties { + secrets { + using project.file('secrets.properties') + } + env { + using System.getenv() + } +} + +/* + * Gets the version name from the latest Git tag + */ +def getVersionName = { + def stdout = new ByteArrayOutputStream() + try { + exec { + commandLine 'git', 'describe', '--tags', '--abbrev=0' + standardOutput = stdout + } + return stdout.toString().trim() + } + catch (e) { + println("Can't get version from git: " + e) + return "adhoc" + } +} +allprojects { + version = "${getVersionName()}" +} + +/* + * Performs clean, build, maven install and publish on Bintray + */ +task cleanBuildInstallPublish { + dependsOn 'clean' + dependsOn 'build' + dependsOn 'install' + dependsOn 'bintrayUpload' + tasks.findByName('build').mustRunAfter 'clean' + tasks.findByName('install').mustRunAfter 'build' + tasks.findByName('bintrayUpload').mustRunAfter 'install' +} +configure(cleanBuildInstallPublish) { + group = 'Publishing' + description = 'Cleans, builds, creates artifact and uploads to bintray' +} + +/* + * Upload to Bintray + */ +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} +artifacts { + archives sourcesJar +} + +group = 'it.federicoboschini' + +bintray { + user = (buildProperties.secrets['bintray.user'] | buildProperties.env['BINTRAY_USER']).string + key = (buildProperties.secrets['bintray.apikey'] | buildProperties.env['BINTRAY_APIKEY']).string + configurations = ['archives'] + + pkg { + repo = 'android-libraries' + name = 'it.federico:resource-file-provider' + vcsUrl = 'https://github.com/federicoboschini/Android-Resource-File-Provider' + websiteUrl = 'https://federicoboschini.it' + licenses = ['MIT'] + publish = true + } +} \ No newline at end of file diff --git a/resource-file-provider/proguard-rules.pro b/resource-file-provider/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/resource-file-provider/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/resource-file-provider/src/androidTest/java/it/federicoboschini/resourcefileprovider/ExampleInstrumentedTest.java b/resource-file-provider/src/androidTest/java/it/federicoboschini/resourcefileprovider/ExampleInstrumentedTest.java new file mode 100644 index 0000000..0dc12a2 --- /dev/null +++ b/resource-file-provider/src/androidTest/java/it/federicoboschini/resourcefileprovider/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package it.federicoboschini.resourcefileprovider; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("it.federicoboschini.androidresourcefileprovider.test", appContext.getPackageName()); + } +} diff --git a/resource-file-provider/src/main/AndroidManifest.xml b/resource-file-provider/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ab8e5ce --- /dev/null +++ b/resource-file-provider/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/resource-file-provider/src/main/java/it/federicoboschini/resourcefileprovider/ResourceFileProvider.java b/resource-file-provider/src/main/java/it/federicoboschini/resourcefileprovider/ResourceFileProvider.java new file mode 100644 index 0000000..f52c7a3 --- /dev/null +++ b/resource-file-provider/src/main/java/it/federicoboschini/resourcefileprovider/ResourceFileProvider.java @@ -0,0 +1,212 @@ +package it.federicoboschini.resourcefileprovider; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; +import android.net.Uri; +import android.support.annotation.NonNull; +import android.support.v4.app.ShareCompat; +import android.support.v4.content.FileProvider; +import android.util.Log; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.IllegalFormatException; + +import it.federicoboschini.androidresourcefileprovider.R; + +/** + * @author Federico Boschini + */ +public class ResourceFileProvider { + + private static final String TAG = "ResourceFileProvider"; + + private static final String ANDROID_RES_URI = "android.resource://%1$s/%2$s"; + + public static final String FOLDER_RAW = "raw"; + public static final String FOLDER_DRAWABLE = "drawable"; + public static final String FOLDER_MIPMAP = "mipmap"; + public static final String FOLDER_ASSETS = "assets"; + + public static final String TYPE_AUDIO = "audio/*"; + public static final String TYPE_IMAGE = "image/*"; + public static final String TYPE_VIDEO = "video/*"; + public static final String TYPE_PDF = "application/pdf"; + + private final Activity activity; + private final String directory; + private final String fileName; + private final String fileExtension; + private final String fileType; + + private ResourceFileProvider(@NonNull Activity activity, @NonNull String directory, @NonNull String fileName, @NonNull String fileExtension, @NonNull String fileType) { + this.activity = activity; + this.directory = directory; + this.fileName = fileName; + this.fileExtension = fileExtension; + this.fileType = fileType; + } + + /** + * Given the {@link Builder} parameters, retrieves the file. Automatically starts a "share" Intent. + * @throws FileNotFoundException if can't find the file. + */ + public void shareFile() throws FileNotFoundException { + int resId = activity.getResources().getIdentifier(fileName, directory, activity.getPackageName()); + InputStream inputStream = null; + if (isValidResId(resId)) { + switch (directory) { + case FOLDER_RAW: + inputStream = activity.getResources().openRawResource(resId); + break; + case FOLDER_MIPMAP: + case FOLDER_DRAWABLE: + Uri fileUri; + try { + fileUri = Uri.parse(String.format(ANDROID_RES_URI, activity.getPackageName(), resId)); + } catch (IllegalFormatException e) { + throw new FileNotFoundException(); + } + if (fileUri != null) { + inputStream = activity.getContentResolver().openInputStream(fileUri); + } + break; + default: + inputStream = activity.getResources().openRawResource(resId); + break; + } + prepareAndShare(inputStream); + } else { + if (directory.equals(FOLDER_ASSETS)) { + AssetManager assetManager = activity.getAssets(); + try { + inputStream = assetManager.open(fileName.concat(".").concat(fileExtension)); + } catch (IOException e) { + e.printStackTrace(); + throw new FileNotFoundException(); + } + prepareAndShare(inputStream); + } else { + throw new FileNotFoundException(); + } + } + } + + private void prepareAndShare(InputStream inputStream) { + try { + byte[] buff = new byte[1024]; + int len; + FileOutputStream outputStream = activity.openFileOutput(fileName.concat(".").concat(fileExtension), Context.MODE_PRIVATE); + if (inputStream != null) { + while ((len = inputStream.read(buff)) > 0) { + outputStream.write(buff, 0, len); + } + inputStream.close(); + } + outputStream.close(); + } catch (IOException e) { + Log.e(TAG, e.getLocalizedMessage()); + } + + Uri uri = FileProvider.getUriForFile(activity, activity.getResources().getString(R.string.rfp_provider_authority), new File(activity.getFilesDir(), fileName.concat(".").concat(fileExtension))); + + Intent intent = ShareCompat.IntentBuilder.from(activity).getIntent(); + intent.setAction(Intent.ACTION_SEND); + intent.setType(fileType); + intent.putExtra(Intent.EXTRA_STREAM, uri); + intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + + if (intent.resolveActivity(activity.getPackageManager()) != null) { + activity.startActivity(intent); + } + } + + private boolean isValidResId(int resId) { + return resId != 0; + } + + /** + * Builder class: the entry point of this tool. + */ + public static class Builder { + private final Activity activity; + private String directory; + private String fileName; + private String fileExtension; + private String fileType; + + private Builder(Activity activity) { + this.activity = activity; + } + + /** + * @param activity a valid Activity used as Context and to start the "share" Intent + * @return the Builder itself. + */ + public static Builder from(@NonNull Activity activity) { + return new Builder(activity); + } + + /** + * Set the directory where the file is stored. + * @param directory a String representing the directory. Consider using one of the following + * {@link ResourceFileProvider#FOLDER_ASSETS} + * {@link ResourceFileProvider#FOLDER_RAW} + * {@link ResourceFileProvider#FOLDER_DRAWABLE} + * @return the Builder itself. + */ + public Builder setDirectory(@NonNull String directory) { + this.directory = directory; + return this; + } + + /** + * Set the file name. + * @param fileName the filename as a String, WITHOUT any extension, see {@link Builder#setFileExtension(String)}. + * @return the Builder itself. + */ + public Builder setFileName(@NonNull String fileName) { + this.fileName = fileName; + return this; + } + + /** + * Set the file extension. + * @param fileExtension the extension as a String, WITHOUT the point. + * @return the Builder itself. + */ + public Builder setFileExtension(@NonNull String fileExtension) { + this.fileExtension = fileExtension; + return this; + } + + /** + * Set the file type. Used for the "share" intent. + * @param fileType the file type as a String (MIME type). Consider using one of the following + * {@link ResourceFileProvider#TYPE_AUDIO} + * {@link ResourceFileProvider#TYPE_VIDEO} + * {@link ResourceFileProvider#TYPE_IMAGE} + * {@link ResourceFileProvider#TYPE_PDF} + * @return the Builder itself. + */ + public Builder setFileType(@NonNull String fileType) { + this.fileType = fileType; + return this; + } + + /** + * Builds the ResourceFileProvider. + * @return the ResourceFileProvider. + */ + public ResourceFileProvider build() { + return new ResourceFileProvider(activity, directory, fileName, fileExtension, fileType); + } + } + + +} diff --git a/resource-file-provider/src/main/res/values/strings.xml b/resource-file-provider/src/main/res/values/strings.xml new file mode 100644 index 0000000..10f73e2 --- /dev/null +++ b/resource-file-provider/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + it.federicoboschini.fileprovider + diff --git a/resource-file-provider/src/main/res/xml/file_provider_paths.xml b/resource-file-provider/src/main/res/xml/file_provider_paths.xml new file mode 100644 index 0000000..cffb2c3 --- /dev/null +++ b/resource-file-provider/src/main/res/xml/file_provider_paths.xml @@ -0,0 +1,4 @@ + + + + diff --git a/resource-file-provider/src/test/java/it/federicoboschini/resourcefileprovider/ExampleUnitTest.java b/resource-file-provider/src/test/java/it/federicoboschini/resourcefileprovider/ExampleUnitTest.java new file mode 100644 index 0000000..7c0b28d --- /dev/null +++ b/resource-file-provider/src/test/java/it/federicoboschini/resourcefileprovider/ExampleUnitTest.java @@ -0,0 +1,17 @@ +package it.federicoboschini.resourcefileprovider; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/sample/.gitignore b/sample/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/sample/.gitignore @@ -0,0 +1 @@ +/build diff --git a/sample/build.gradle b/sample/build.gradle new file mode 100644 index 0000000..3b275c8 --- /dev/null +++ b/sample/build.gradle @@ -0,0 +1,33 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 28 + defaultConfig { + applicationId "it.federicoboschini.arfp.sample" + minSdkVersion 14 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + + //implementation 'it.federicoboschini:resource-file-provider:1.0.0' + implementation project(':resource-file-provider') + + implementation 'com.android.support:appcompat-v7:28.0.0' + + implementation 'com.android.support.constraint:constraint-layout:1.1.3' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' +} diff --git a/sample/proguard-rules.pro b/sample/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/sample/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/sample/src/androidTest/java/it/federicoboschini/fileprovidersample/ExampleInstrumentedTest.java b/sample/src/androidTest/java/it/federicoboschini/fileprovidersample/ExampleInstrumentedTest.java new file mode 100644 index 0000000..2ce74a1 --- /dev/null +++ b/sample/src/androidTest/java/it/federicoboschini/fileprovidersample/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package it.federicoboschini.fileprovidersample; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("it.federicoboschini.androidresourcefileprovider", appContext.getPackageName()); + } +} diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..10d141c --- /dev/null +++ b/sample/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/sample/src/main/assets/loremipsum.pdf b/sample/src/main/assets/loremipsum.pdf new file mode 100644 index 0000000..22ace57 Binary files /dev/null and b/sample/src/main/assets/loremipsum.pdf differ diff --git a/sample/src/main/assets/pokeflute.png b/sample/src/main/assets/pokeflute.png new file mode 100644 index 0000000..b16e846 Binary files /dev/null and b/sample/src/main/assets/pokeflute.png differ diff --git a/sample/src/main/assets/yee.mp3 b/sample/src/main/assets/yee.mp3 new file mode 100644 index 0000000..66536c4 Binary files /dev/null and b/sample/src/main/assets/yee.mp3 differ diff --git a/sample/src/main/assets/yee_video.mp4 b/sample/src/main/assets/yee_video.mp4 new file mode 100644 index 0000000..ba49a2a Binary files /dev/null and b/sample/src/main/assets/yee_video.mp4 differ diff --git a/sample/src/main/java/it/federicoboschini/fileprovidersample/MainActivity.java b/sample/src/main/java/it/federicoboschini/fileprovidersample/MainActivity.java new file mode 100644 index 0000000..4247ad1 --- /dev/null +++ b/sample/src/main/java/it/federicoboschini/fileprovidersample/MainActivity.java @@ -0,0 +1,164 @@ +package it.federicoboschini.fileprovidersample; + +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.View; + +import java.io.FileNotFoundException; + +import it.federicoboschini.resourcefileprovider.ResourceFileProvider; +import it.federicoboschini.arfp.sample.R; + +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.FOLDER_ASSETS; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.FOLDER_DRAWABLE; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.FOLDER_MIPMAP; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.FOLDER_RAW; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.TYPE_AUDIO; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.TYPE_IMAGE; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.TYPE_PDF; +import static it.federicoboschini.resourcefileprovider.ResourceFileProvider.TYPE_VIDEO; + +public class MainActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + } + + public void shareRawSoundFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_RAW) + .setFileName("yee") + .setFileExtension("mp3") + .setFileType(TYPE_AUDIO) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareAssetsSoundFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_ASSETS) + .setFileName("yee") + .setFileExtension("mp3") + .setFileType(TYPE_AUDIO) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareAssetsPdfFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_ASSETS) + .setFileName("loremipsum") + .setFileExtension("pdf") + .setFileType(TYPE_PDF) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareRawPdfFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_RAW) + .setFileName("loremipsum") + .setFileExtension("pdf") + .setFileType(TYPE_PDF) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareRawVideoFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_RAW) + .setFileName("yee_video") + .setFileExtension("mp4") + .setFileType(TYPE_VIDEO) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareAssetsVideoFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_ASSETS) + .setFileName("yee_video") + .setFileExtension("mp4") + .setFileType(TYPE_VIDEO) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareImageAssets(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_ASSETS) + .setFileName("pokeflute") + .setFileExtension("png") + .setFileType(TYPE_IMAGE) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareImageRaw(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_RAW) + .setFileName("pokeflute") + .setFileExtension("png") + .setFileType(TYPE_IMAGE) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void shareDrawableFile(View view) { + try { + ResourceFileProvider.Builder + .from(this) + .setDirectory(FOLDER_DRAWABLE) + .setFileName("pokeflute") + .setFileExtension("png") + .setFileType(TYPE_IMAGE) + .build() + .shareFile(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + +} diff --git a/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml b/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/sample/src/main/res/drawable/ic_launcher_background.xml b/sample/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/sample/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sample/src/main/res/drawable/pokeflute.png b/sample/src/main/res/drawable/pokeflute.png new file mode 100644 index 0000000..b16e846 Binary files /dev/null and b/sample/src/main/res/drawable/pokeflute.png differ diff --git a/sample/src/main/res/layout/activity_main.xml b/sample/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..2f7f4eb --- /dev/null +++ b/sample/src/main/res/layout/activity_main.xml @@ -0,0 +1,104 @@ + + + + + +