How to add the API key to use Google Cloud TTS? - android

I am trying to create a simple testing app for Cloud TTS. The official documentation does not seem to provide any specific information about Android, and the closest thing was Java.
I created a default app and then added the library like this,
implementation 'com.google.cloud:google-cloud-texttospeech:0.82.0-beta'
which caused a weird build error, so I added this after reading an existing StackOverflow question
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
exclude 'META-INF/INDEX.LIST'
}
Now it compiles, but of course it caused a runtime exception saying that GOOGLE_APPLICATION_CREDENTIALS must be defined. But how to do that with Android? The documentation page only had instructions for Windows/Linux/macOS.
In case someone sees this question in the future, I think I solved this by doing what this page does. I copied the credential.json to the raw directory, and did the following thing before calling the API.
val cred = ServiceAccountCredentials.fromStream(resources.openRawResource(R.raw.credentials));
val buil = TextToSpeechSettings.newBuilder();
buil.credentialsProvider = FixedCredentialsProvider.create(cred);
val sett = buil.build();
// Instantiates a client
TextToSpeechClient.create(sett).use { textToSpeechClient ->

Here is an example for Google Cloud TTS.
You can read the issue about Google Cloud TTS Github Issues.
Google Cloud TTS does not currently support the android.
You can use Restful API to get audio Base64 encoding and use MediaPlayer library to play audio.

Copy your credential information which contains type, private_key
Write content of Step 1 into credential.json file.
Copy file of Step 2 into /res/raw folder. (If it's not working, put file into assets folder.)
Or, you can parse environment variables and write into credential.json file.
Below code comes from GoogleCloudPlatform/android-docs-samples.
task copySecretKey(type: Copy) {
def File secretKey = file "$System.env.GOOGLE_APPLICATION_CREDENTIALS"
from secretKey.getParent()
include secretKey.getName()
into 'src/main/res/raw'
rename secretKey.getName(), "credential.json"
}

Related

Protect html/css/js on Android asesst folder

I working an Android application. Some activities, I used webview and load html from Android asesst folder. On apk if rename package to name.apk.zip then anyone can easily access my asesst folder content.
Now I want to protect my assect content mainly html files.
Please help to give some suggest about html encryption or Android studio plugins about protection.
Most efficient way to do this, it's include that files in your Server, and getting files by authorization.
To do it locally. I suggest to create custom task in gradle for mapping your html/css files in some incode storage, with Base64 (encoding just for ex.). It's looks like:
task mapAssets(dependsOn: build) {
SOURCE_FILE = 'Path to Source File'
doFirst {
println "I'm Gradle"
}
String source = new File(SOURCE_FILE).text
ENCODED_FILE = 'Path to Encoded File'
new File(ENCODED_FILE).withWriter { out ->
out.println source.bytes.encodeBase64().toString()
}
}
Later in your Java code, just find ENCODED_FILE and make call with reading file and mapping again in HTML, from Base64 (or any other encoding).

How to include and read source map file in React Native on Android

I am trying to generate source maps in the Gradle build process of a React Native app and read the source map file in the application.
I used this project as a starting point: https://github.com/philipshurpik/react-native-source-maps
I didn't succeed in including it as it is, so I tried to take and modify parts of it.
In app/gradle.build I added:
project.ext.react = [
extraPackagerArgs: ["--sourcemap-output", "$buildDir/intermediates/assets/release/index.map"]
]
and indeed when I'm running the release build I see the file index.map under android/app/build/intermediates/assets/release , but when I deploy the APK to a device or emulator, I can't see this file anywhere in Android's filesystem. For that matter, I also can't see the bundle file or any files that were in android/app/src/main/assets and I do see in android/app/build/intermediates/assets/release after build.
The application code uses https://github.com/itinance/react-native-fs to read the file. This is how I first check if the file exists:
const fileExists = await RNFS.existsAssets(`${RNFS.DocumentDirectoryPath}/index.map`)
and the file doesn't exist there. RNFS.DocumentDirectoryPath returns /data/user/0/mypackagename/files , which is empty when I check (using adb shell with root access).
What am I missing? How do I get the source map file to a location which will be available to the application to read?
Turned out the gradle.build part was fine, and in order to read the source map file I needed to use just the file name, like so: RNFS.existsAssets('index.map')

What is Google Application Credential?

I am using Google Speech API in My Android application and I am taking reference with the sample application provided by Google in docs.
In this sample, there are several lines for the authentication process in App level gradle file.
task copySecretKey(type: Copy) {
def File secretKey = file "$System.env.GOOGLE_APPLICATION_CREDENTIALS"
from secretKey.getParent()
include secretKey.getName()
into 'src/main/res/raw'
rename secretKey.getName(), "credential.json"}
preBuild.dependsOn(copySecretKey)
In this code, I am not getting what is GOOGLE_APPLICATION_CREDENTIALS and where I should paste my JSON.
Thanks in Advance.
file is the location of your json file. they are just showing you how to use the system variable assuming you have that set to the location of said fule

Use Sample data directory from a library

I created Sample data directory for my Android app using the process described in this article. I would like to share this set of sample data between my projects, so I created a library that only has sample data inside. But as far as I can see sampledata folder is not being compiled into the library. Is there a way to share sample data between multiple Android projects?
As already said, you can't do that with a library because sampledata simply can't be part of an Android library.
One thing you could though, host your names file somewhere and then fetch it with a gradle task, you could just add to an app's build.gradle
clean.doFirst {
println "cleanSamples"
def samplesDir = new File(projectDir.absolutePath, "sampledata")
if (samplesDir.exists()) {
samplesDir.deleteDir()
}
}
task fetchSamples {
println "fetchSamples"
def samplesDir = new File(projectDir.absolutePath, "sampledata")
if (samplesDir.exists()) {
println "samples dir already exists"
return
}
samplesDir.mkdir()
def names = new File(samplesDir, "names")
new URL('http://path/to/names').withInputStream { i ->
names.withOutputStream {
it << i
}
}
}
You can see 2 functions there, the first one is run before a clean task and it will just delete your sampledata folder. The second one is a task run on every build, it won't download the file every time but only if the directory is not there.
I understand you might as well copy paste names file, but, with this method you need to copy paste the tasks only once and you would be able to change names in any project just by uploading a new file and doing a clean build.
The short answer is no, you can't do that with sampledata folder. Basically, the format of the Android Libraries is AAR. If you reference the official documentation, it says that:
The file itself is a zip file containing the following mandatory entries:
/AndroidManifest.xml
/classes.jar
/res/
/R.txt
/public.txt
Additionally, an AAR file may include one or more of the following optional entries:
/assets/
/libs/name.jar
/jni/abi_name/name.so (where abi_name is one of the Android supported ABIs)
/proguard.txt
/lint.jar
So, sampledata can't be a part of AAR library.
UPDATE
Instead of your own data samples, you can use predefined sample resources. For example #tools:sample/first_names will randomly select from some common first names, eg., Sophia, Jacob, Ivan.
Example of usage:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="#tools:sample/first_names" />

openalpr on android - path to config and runtime_data

I want to use open alpr (automatic licences plate recognition) library in my android project. I compiled everything successfully and now it is time to use open alpr in app but...
to create Alpr class object properly I have to provide path to config file and path to runtime_data folder which contains some mandatory files needed by open alpr (ocr and trained data).
I tried something like:
Alpr alpr = new Alpr("eu", "android_assets/alpr.conf", "android_assets/runtime_data");
but Alpr.isLoaded() returns false which means that config or runtime_data have not been found.
Path to assets folder in project is: src/main/assets.
Can someone explain to me how path to "runtime_data" directory and "alpr.conf"
should looks to be visible by open alpr?
Thanks in advance.
I am not familiar with the specific library, but on newer Android devices (Android 6 and up), you can not rely on your application files residing under /data/data/your.package.name
The actual library name still includes the package name of your app, but also has some identifier appended to it in base64 format.
This identifier is unique per installation, and it will change if you uninstall and reinstall the app on the same device.
So, if your library needs to use a configuration file with a path to some other files, there are 2 options:
The right way:
Get the real address of your application files folder using Context.getFilesDir().
Unpack you files from the assets folder of the APK on the device using AssetManager.
Programmatically rewrite your configuration file with the path returned by getFilesDir().
The "hacky" but simpler way:
Use public storage to unpack your files.
You will need to add WRITE_EXTERNAL_STORAGE permission to your app, and unpack the assets files to the external storage.
For backwards compatibility this will be available under /sdcard folder on most Android devices, even with the latest Android version.
The second method is not recommended since using /sdcard directly is deprecated and strongly discouraged by Google.
Also, not all Android devices have /sdcard link to their public storage, but this is the only way to avoid dynamically editing the configuration file after installation.
Important note before you start implementing those steps. This library supports only arm CPU architecture. Good news is, most probably, your physical device is using arm architecture but to make sure just double-check it before implemting those steps.
I've recompiled this library to a new wrapper library. In original library, you need to manually configure openalpr.conf file and edit its content with correct path to your data directory. Manual configuration is cumbersome because since Android 5 multiple user accounts is supported and we can't simply hardcode data directory as /data/data/com.your.packagename/..... Because every user gets their symlink to data directory as /data/user/0/com.your.packagename/..... All those manual steps are gone in recompiled wrapper library.
Implementation
Add this in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Add the dependency into app module:
dependencies {
...
implementation 'com.github.mecoFarid:openalpr:1.0.0'
}
And you're done. Please check this sample app to get started with UI.
Troubleshooting:
If your target sdk is targetSdkVersion >= 24 and you're running your app on a device with Android API 24+ you'll get following error:
android.os.FileUriExposedException: file:///storage/emulated/0/OpenALPR/2019-09-21-01-32-13.jpg exposed beyond app through ClipData.Item.getUri()
To solve this error: you can add following lines into onCreate() of your Activity as a workaround or you may use this thread for offical solution:
if(Build.VERSION.SDK_INT>=24){
try{
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
}catch(Exception e){
e.printStackTrace();
}
}
TEST:
You can use this image to test your app.
"/data/data/yourpackagename" + File.separatorChar + "runtime_data"
+ File.separatorChar + "openalpr.conf";

Categories

Resources