Cleaner solution for Gingerbread problems: use AsyncTask instead of Runnable

ref #18
This commit is contained in:
Felix Ableitner 2014-06-22 18:56:16 +02:00
parent 5ba80e5bfa
commit 7b2ef0d6a0
1 changed files with 89 additions and 73 deletions

View File

@ -6,10 +6,12 @@ import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.util.Pair;
import com.nutomic.syncthingandroid.R;
import com.nutomic.syncthingandroid.WebGuiActivity;
@ -129,7 +131,9 @@ public class SyncthingService extends Service {
/**
* Runs the syncthing binary from command line, and prints its output to logcat (on exit).
*/
private void runNative() {
private class SyncthingRunnable implements Runnable {
@Override
public void run() {
DataOutputStream dos = null;
int ret = 1;
Process process = null;
@ -165,6 +169,7 @@ public class SyncthingService extends Service {
}
}
}
}
/**
* Logs the outputs of a stream to logcat and mNativeLog.
@ -292,10 +297,17 @@ public class SyncthingService extends Service {
n.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, n);
new Thread(new Runnable() {
new StartupTask().execute();
}
/**
* Sets up the initial configuration, updates the config when coming from an old
* version, and reads syncthing URL and API key (these are passed internally as
* {@code Pair<String, String>}.
*/
private class StartupTask extends AsyncTask<Void, Void, Pair<String, String>> {
@Override
public void run() {
Looper.prepare();
protected Pair<String, String> doInBackground(Void... voids) {Looper.prepare();
if (isFirstStart(SyncthingService.this)) {
Log.i(TAG, "App started for the first time. " +
"Copying default config, keys will be generated automatically");
@ -324,18 +336,22 @@ public class SyncthingService extends Service {
throw new RuntimeException("Failed to read gui url, aborting", e);
}
finally {
mApi = new RestApi("http://" + syncthingUrl, apiKey);
return new Pair<String, String>("http://" + syncthingUrl, apiKey);
}
}
@Override
protected void onPostExecute(Pair<String, String> urlAndKey) {
mApi = new RestApi(urlAndKey.first, urlAndKey.second);
Log.i(TAG, "Web GUI will be available at " + mApi.getUrl());
// HACK: Make sure there is no syncthing binary left running from an improper
// shutdown (eg Play Store update).
// NOTE: This will log an exception if syncthing is not actually running.
new PostTask().execute(mApi.getUrl(), PostTask.URI_SHUTDOWN, apiKey);
new PostTask().execute(mApi.getUrl(), PostTask.URI_SHUTDOWN, urlAndKey.second);
registerOnWebGuiAvailableListener(mApi);
}
new PollWebGuiAvailableTask().execute();
runNative();
new Thread(new SyncthingRunnable()).start();
}
}).start();
}
@Override