Added own crash handler for debugging
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / CampusAppExceptionHandler.java
diff --git a/app/src/main/java/de/dhbwloe/campusapp/CampusAppExceptionHandler.java b/app/src/main/java/de/dhbwloe/campusapp/CampusAppExceptionHandler.java
new file mode 100644 (file)
index 0000000..9d5a974
--- /dev/null
@@ -0,0 +1,143 @@
+package de.dhbwloe.campusapp;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.util.Log;
+
+import com.loopj.android.http.AsyncHttpClient;
+import com.loopj.android.http.AsyncHttpResponseHandler;
+import com.loopj.android.http.RequestParams;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import cz.msebera.android.httpclient.Header;
+import cz.msebera.android.httpclient.NameValuePair;
+import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
+import cz.msebera.android.httpclient.client.methods.HttpPost;
+import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
+import cz.msebera.android.httpclient.message.BasicNameValuePair;
+import cz.msebera.android.httpclient.protocol.HTTP;
+
+/**
+ * Created by pk910 on 11.03.2016.
+ */
+public class CampusAppExceptionHandler {
+    private static String CRASHLOG_UPLOAD = "http://dev.pk910.de/DHBWCampusCourses";
+    private String localPath;
+
+    private static boolean crashLogWindowOpened = false;
+
+    public void handleUncaughtException(Thread thread, Throwable e) {
+        // automatically send crash log to my server for debuggging.
+        // disable this for productive use! (CampusAppContext.DEBUG)
+
+        final Writer result = new StringWriter();
+        final PrintWriter printWriter = new PrintWriter(result);
+        e.printStackTrace(printWriter);
+        String stacktrace = result.toString();
+        printWriter.close();
+
+        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
+        String crashdate = dateFormat.format(new Date());
+        String filename = crashdate + ".stacktrace";
+
+        CampusAppContext context;
+        Activity mainActivity = null;
+        try {
+            /*Wir greifen nun auf einen Code zurück, aus welchem die unbehandelte Exception stammt.
+            * Dies ist womöglich keine gute Idee, daher müssen wir sämmtliche Exceptions abfangen und verwerfen (Exception inception :D)
+            * und hoffen, dass die App noch so weit "funktioniert" ;)
+            */
+            context = CampusAppContext.getInstance();
+
+            if(context != null) {
+                mainActivity = context.getMainActivity();
+            }
+            if(mainActivity != null) {
+                localPath = mainActivity.getApplicationContext().getFilesDir().getAbsolutePath();
+            }
+        } catch (Exception ex) {}
+
+        if(localPath != null)
+            writeToFile(stacktrace, filename);
+
+        // start crash screen
+        if(!crashLogWindowOpened) {
+            try {
+                Intent intent = new Intent();
+                intent.setAction("de.dhbw.campusapp.CRASH_LOG");
+                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
+                intent.putExtra("crashdate", crashdate);
+                mainActivity.startActivity(intent);
+                crashLogWindowOpened = true;
+            } catch (Exception ex) {
+            }
+        }
+    }
+
+    private void writeToFile(String stacktrace, String filename) {
+        try {
+            BufferedWriter bos = new BufferedWriter(new FileWriter(
+                    localPath + "/" + filename));
+            bos.write(stacktrace);
+            bos.flush();
+            bos.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public void postprocessException(Activity crashLogScreen, String crashdate) {
+        localPath = crashLogScreen.getApplicationContext().getFilesDir().getAbsolutePath();
+        String fileName = localPath + "/" + crashdate + ".stacktrace";
+        StringBuilder stackTrace = new StringBuilder();
+
+        try {
+            BufferedReader br = new BufferedReader(new FileReader(fileName));
+            String line;
+
+            while ((line = br.readLine()) != null) {
+                stackTrace.append(line);
+                stackTrace.append('\n');
+            }
+            br.close();
+        }
+        catch (IOException e) {
+            //You'll need to add proper error handling here
+        }
+
+        sendToServer(CRASHLOG_UPLOAD, stackTrace.toString(), crashdate);
+    }
+
+    private void sendToServer(String url, String stacktrace, String crashdate) {
+        AsyncHttpClient client = new AsyncHttpClient();
+        RequestParams params = new RequestParams();
+        params.add("stacktrace", stacktrace);
+        params.add("crashdate", crashdate);
+
+        client.post(url, params, new AsyncHttpResponseHandler() {
+
+            @Override
+            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
+                Log.i("CrashLog", "OK: "+(responseBody != null ? new String(responseBody) : null));
+            }
+
+            @Override
+            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
+                Log.i("CrashLog", "Failed: "+(responseBody != null ? new String(responseBody) : null));
+            }
+        });
+    }
+
+}