Skip to content

Commit

Permalink
Added perf quickstart.
Browse files Browse the repository at this point in the history
Change-Id: I4f4ced1315edb4ed334d5f87d1ccd0047448af4b
  • Loading branch information
Kalyan Reddy committed May 16, 2017
1 parent 974a9df commit 37e524f
Show file tree
Hide file tree
Showing 30 changed files with 729 additions and 0 deletions.
9 changes: 9 additions & 0 deletions perf/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.gradle
*.iml
/.idea/libraries
/.idea/workspace.xml
.DS_Store
/build
/local.properties
.idea/
google-services.json
1 change: 1 addition & 0 deletions perf/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
44 changes: 44 additions & 0 deletions perf/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.firebase-perf'

android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.google.firebase.quickstart.perfmon"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

android.applicationVariants.all {
// Set this to false to disable Firebase Performance Monitoring at compile time
FirebasePerformance {
instrumentationEnabled true
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.google.firebase:firebase-core:10.2.6'
compile 'com.google.firebase:firebase-perf:10.2.6'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
25 changes: 25 additions & 0 deletions perf/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/google/home/gkal/Android/Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:

# 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.google.firebase.quickstart.perfmon;

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.*;

/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();

assertEquals("com.google.firebase.quickstart.perfmon", appContext.getPackageName());
}
}
21 changes: 21 additions & 0 deletions perf/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.firebase.quickstart.perfmon">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
7 changes: 7 additions & 0 deletions perf/app/src/main/assets/default_content.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
This is the main text content.

Here are some random strings:
x3EIZZm4Z0J0ngq2S3L1jf2wr4DW
H0OnfpDjhRZMAbV9hLFMUTrjqhoV
KUuRv6ulGEme3layWx86qQrzHt1p
J5Qfx737fBhfOAobnt9CxilIgPQ2
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package com.google.firebase.quickstart.perfmon;

import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.firebase.perf.FirebasePerformance;
import com.google.firebase.perf.metrics.Trace;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ImageView mHeader;
private TextView mContent;
private Trace mTrace;
private String STARTUP_TRACE_NAME = "startup_trace";
private String REQUESTS_COUNTER_NAME = "requests sent";
private String FILE_SIZE_COUNTER_NAME = "file size";
private CountDownLatch mNumStartupTasks = new CountDownLatch(2);
private final String DEFAULT_CONTENT_FILE = "default_content.txt";
private final String CONTENT_FILE = "content.txt";
private final String IMAGE_URL =
"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mHeader = (ImageView) findViewById(R.id.imageView);
mContent = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// write 40 chars of random text to file
File contentFile = new File(MainActivity.this.getFilesDir(), CONTENT_FILE);
new WriteToFileTask(contentFile.getAbsolutePath()).execute(getRandomString(40) + "\n");
}
});

// Begin tracing app startup tasks.
mTrace = FirebasePerformance.getInstance().newTrace(STARTUP_TRACE_NAME);
Log.d(TAG, "Starting trace");
mTrace.start();
loadImageFromWeb();
// Increment the counter of number of requests sent in the trace.
Log.d(TAG, "Incrementing number of requests counter in trace");
mTrace.incrementCounter(REQUESTS_COUNTER_NAME);
loadFileFromDisk();
// Wait for app startup tasks to complete asynchronously and stop the trace.
new Thread(new Runnable() {
@Override
public void run() {
try {
mNumStartupTasks.await();
} catch (InterruptedException e) {
Log.e(TAG, "Unable to wait for startup task completion.");
} finally {
Log.d(TAG, "Stopping trace");
mTrace.stop();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Trace completed",
Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}

private void loadImageFromWeb() {
Glide.with(this).
load(IMAGE_URL)
.placeholder(new ColorDrawable(ContextCompat.getColor(this, R.color.colorAccent)))
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
mNumStartupTasks.countDown(); // Signal end of image load task.
return false;
}

@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
mNumStartupTasks.countDown(); // Signal end of image load task.
return false;
}
}).into(mHeader);
}

private void loadFileFromDisk() {
new AsyncTask<Void, Void, Boolean>(){
private String fileContent;

@Override
protected Boolean doInBackground(Void... params) {
File contentFile = new File(MainActivity.this.getFilesDir(), CONTENT_FILE);
try {
if (contentFile.createNewFile()) {
// Content file exist did not exist in internal storage and new file was created.
// Copy in the default content.
InputStream is;
is = getAssets().open(DEFAULT_CONTENT_FILE);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(contentFile);
fos.write(buffer);
fos.close();
}
FileInputStream fis = new FileInputStream(contentFile);
byte[] content = new byte[(int) contentFile.length()];
fis.read(content);
fileContent = new String(content);
return true;

} catch (IOException e) {
return false;
}
}

@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (!result) {
Log.e(TAG, "Couldn't read text file.");
Toast.makeText(MainActivity.this, getString(R.string.text_read_error),
Toast.LENGTH_LONG).show();
return;
}
mContent.setText(fileContent);
// Increment a counter with the file size that was read.
Log.d(TAG, "Incrementing file size counter in trace");
mTrace.incrementCounter(FILE_SIZE_COUNTER_NAME, fileContent.getBytes().length);
mNumStartupTasks.countDown();
}
}.execute();
}

private String getRandomString(int length) {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}

private class WriteToFileTask extends AsyncTask<String, Void, Void> {
private String filename;

WriteToFileTask(String filename) {
this.filename = filename;
}

@Override
protected Void doInBackground(String... params) {
String content = params[0];
try (FileOutputStream fos = new FileOutputStream(filename, true)){
fos.write(content.getBytes());
} catch (IOException e) {
Log.e(TAG, "Unable to write to file: " + filename);
Log.e(TAG, Log.getStackTraceString(e));
}
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
loadFileFromDisk();
}
}
}
Loading

0 comments on commit 37e524f

Please sign in to comment.