Skip to content

Instantly share code, notes, and snippets.

@kpgalligan
Created December 4, 2014 18:41
Show Gist options
  • Save kpgalligan/7cb184a7f5493e87f208 to your computer and use it in GitHub Desktop.
Save kpgalligan/7cb184a7f5493e87f208 to your computer and use it in GitHub Desktop.
Default exception handler on wear
package co.touchlab.wearcrashanalytics;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import com.google.gson.Gson;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Created by kgalligan on 12/4/14.
*/
public class ExceptionHandler implements Thread.UncaughtExceptionHandler
{
public static final String CRASH_PATH = "/msg/crash";
private Thread.UncaughtExceptionHandler defExHandler;
private Context context;
public ExceptionHandler(Context context, Thread.UncaughtExceptionHandler defExHandler)
{
this.context = context;
this.defExHandler = defExHandler;
}
public static void init(Context context)
{
Thread.UncaughtExceptionHandler defExHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(defExHandler instanceof ExceptionHandler))
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(context.getApplicationContext(), defExHandler));
}
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
//Originally ignoring OutOfMemory, but we'll try to log that now.
//TODO: init all data objects when setting up the handler, to conserve memory usage when triggered
try
{
sendCrash(context, new Crash(ex, null));
}
catch (Exception e)
{
//Whoops
}
finally
{
defExHandler.uncaughtException(thread, ex);
}
}
private void sendCrash(Context context, Crash crash)
{
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API)
.build();
String json = new Gson().toJson(crash);
googleApiClient.blockingConnect();
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient)
.await();
for(Node node : nodes.getNodes())
{
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(googleApiClient,
node.getId(),
CRASH_PATH,
json.getBytes())
.await();
if(! result.getStatus()
.isSuccess())
{
Log.e("test", "error");
}
}
}
static class Crash
{
public final String exception;
public final String log;
public Crash(Throwable exception, String log)
{
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
printWriter.close();
this.exception = stringWriter.toString();
this.log = log;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment