Last active
December 4, 2019 15:53
-
-
Save DayS/6310265041ea255799f2023b19f4c4c2 to your computer and use it in GitHub Desktop.
Listener to automatically upload LeakCanary's heap dump analysis on Firebase Storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.os.Build; | |
import android.widget.Toast; | |
import com.google.firebase.storage.FirebaseStorage; | |
import com.google.firebase.storage.StorageMetadata; | |
import com.google.firebase.storage.StorageReference; | |
import org.jetbrains.annotations.NotNull; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import leakcanary.OnHeapAnalyzedListener; | |
import shark.HeapAnalysis; | |
import shark.HeapAnalysisSuccess; | |
public class OnHeapAnalyzedUploaderListener implements OnHeapAnalyzedListener { | |
private Context context; | |
private OnHeapAnalyzedListener delegate; | |
private FirebaseStorage storage = FirebaseStorage.getInstance(); | |
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH); | |
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH-mm-ss", Locale.ENGLISH); | |
public OnHeapAnalyzedUploaderListener(Context context, OnHeapAnalyzedListener delegate) { | |
this.context = context; | |
this.delegate = delegate; | |
} | |
@Override | |
public void onHeapAnalyzed(@NotNull HeapAnalysis heapAnalysis) { | |
this.delegate.onHeapAnalyzed(heapAnalysis); | |
if (heapAnalysis instanceof HeapAnalysisSuccess) { | |
HeapAnalysisSuccess heapAnalysisSuccess = (HeapAnalysisSuccess) heapAnalysis; | |
Date now = new Date(heapAnalysisSuccess.getCreatedAtTimeMillis()); | |
StorageReference leakCanaryRef = storage.getReference("leakcanary/"); | |
StorageReference dateRef = leakCanaryRef.child(dateFormat.format(now)); | |
StorageReference analysisRef = dateRef.child(timeFormat.format(now) + "_" + Build.MODEL.replaceAll("[^a-zA-Z0-9._-]", "-")); | |
StorageMetadata metadata = new StorageMetadata.Builder() | |
.setContentType("text/plain;charset=utf-8") | |
.setCustomMetadata("app_version", BuildConfig.VERSION_NAME) | |
.build(); | |
Logger.debug("Uploading LeakCanary report"); | |
analysisRef.putBytes(heapAnalysis.toString().getBytes(), metadata) | |
.addOnFailureListener(exception -> Toast.makeText(context, "Couldn't upload LeakCanary report: " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show()) | |
.addOnSuccessListener(taskSnapshot -> Toast.makeText(context, "LeakCanary report uploaded", Toast.LENGTH_SHORT).show()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment