package org.fox.ttcomics2.sync; import android.annotation.SuppressLint; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.Binder; import android.os.IBinder; import android.util.Log; import org.fox.ttcomics2.BuildConfig; import org.fox.ttcomics2.CommonActivity; import org.fox.ttcomics2.DatabaseHelper; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; public class SyncFolderService extends Service { private final String TAG = this.getClass().getSimpleName(); public final static String INTENT_ACTION_FILE_PROCESSED = "org.fox.ttcomics2.intent.action.FileProcessed"; public final static String INTENT_ACTION_SCAN_COMPLETE = "org.fox.ttcomics2.intent.action.ScanComplete"; private DatabaseHelper m_databaseHelper; private final IBinder m_binder = new LocalBinder(); public class LocalBinder extends Binder { SyncFolderService getService() { return SyncFolderService.this; } } @Override public void onCreate() { super.onCreate(); m_databaseHelper = DatabaseHelper.getInstance(this); } @Override public IBinder onBind(Intent intent) { return m_binder; } @Override public void onStart(Intent intent, int startId) { String baseDir = intent.getExtras().getString("baseDir"); @SuppressLint("StaticFieldLeak") AsyncTask task = new AsyncTask() { @Override protected Integer doInBackground(String... params) { File rootDir = new File(params[0]); if (rootDir.exists() && rootDir.isDirectory()) { int index = 0; int count = rootDir.listFiles().length; for (File file : rootDir.listFiles()) { ++index; Log.d(TAG, "file=" + file.getAbsolutePath()); SyncClient m_syncClient = new SyncClient(); String googleAccount = CommonActivity.getSyncAccount(getApplicationContext()); if (googleAccount != null) { m_syncClient.setOwner(googleAccount); } else if (BuildConfig.DEBUG) { m_syncClient.setOwner("TEST-ACCOUNT"); } HttpURLConnection conn = m_syncClient.doSyncHttpRequest("get", CommonActivity.sha1(file.getName())); try { if (conn != null && conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String result = m_syncClient.readHttpResponse(conn); if (result != null) { //Log.d(TAG, "GOT=" + result); int position = Integer.valueOf(result); if (position > 0) { if (position > m_databaseHelper.getLastPosition(file.getAbsolutePath())) { m_databaseHelper.setLastPosition(file.getAbsolutePath(), position); } } } Thread.sleep(250); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Intent broadcast = new Intent(); broadcast.setAction(INTENT_ACTION_FILE_PROCESSED); broadcast.putExtra("index", index); broadcast.putExtra("count", count); broadcast.addCategory(Intent.CATEGORY_DEFAULT); sendBroadcast(broadcast); } } Intent broadcast = new Intent(); broadcast.setAction(INTENT_ACTION_SCAN_COMPLETE); broadcast.addCategory(Intent.CATEGORY_DEFAULT); sendBroadcast(broadcast); stopSelf(); return null; } }; task.execute(baseDir); } }