Moved downloadservice handler to background task

This commit is contained in:
daniel oeh 2012-07-23 20:58:26 +02:00
parent aebb928a23
commit 40bed42743
1 changed files with 91 additions and 59 deletions

View File

@ -101,7 +101,8 @@ public class DownloadService extends Service {
@SuppressLint("NewApi") @SuppressLint("NewApi")
@Override @Override
public void onCreate() { public void onCreate() {
if (AppConfig.DEBUG) Log.d(TAG, "Service started"); if (AppConfig.DEBUG)
Log.d(TAG, "Service started");
isRunning = true; isRunning = true;
completedDownloads = new ArrayList<DownloadStatus>(); completedDownloads = new ArrayList<DownloadStatus>();
registerReceiver(downloadReceiver, createIntentFilter()); registerReceiver(downloadReceiver, createIntentFilter());
@ -126,7 +127,8 @@ public class DownloadService extends Service {
@Override @Override
public void onDestroy() { public void onDestroy() {
if (AppConfig.DEBUG) Log.d(TAG, "Service shutting down"); if (AppConfig.DEBUG)
Log.d(TAG, "Service shutting down");
isRunning = false; isRunning = false;
sendBroadcast(new Intent(ACTION_FEED_SYNC_COMPLETED)); sendBroadcast(new Intent(ACTION_FEED_SYNC_COMPLETED));
mediaplayer.release(); mediaplayer.release();
@ -143,18 +145,22 @@ public class DownloadService extends Service {
/** Shuts down Executor service and prepares for shutdown */ /** Shuts down Executor service and prepares for shutdown */
private void initiateShutdown() { private void initiateShutdown() {
if (AppConfig.DEBUG) Log.d(TAG, "Initiating shutdown"); if (AppConfig.DEBUG)
Log.d(TAG, "Initiating shutdown");
// Wait until PoolExecutor is done // Wait until PoolExecutor is done
Thread waiter = new Thread() { Thread waiter = new Thread() {
@Override @Override
public void run() { public void run() {
syncExecutor.shutdown(); syncExecutor.shutdown();
try { try {
if (AppConfig.DEBUG) Log.d(TAG, "Starting to wait for termination"); if (AppConfig.DEBUG)
Log.d(TAG, "Starting to wait for termination");
boolean b = syncExecutor.awaitTermination(20L, boolean b = syncExecutor.awaitTermination(20L,
TimeUnit.SECONDS); TimeUnit.SECONDS);
if (AppConfig.DEBUG) Log.d(TAG, "Stopping waiting for termination; Result : " if (AppConfig.DEBUG)
+ b); Log.d(TAG,
"Stopping waiting for termination; Result : "
+ b);
stopSelf(); stopSelf();
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -180,57 +186,74 @@ public class DownloadService extends Service {
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim); .setSmallIcon(android.R.drawable.stat_notify_sync_noanim);
startForeground(NOTIFICATION_ID, notificationBuilder.getNotification()); startForeground(NOTIFICATION_ID, notificationBuilder.getNotification());
if (AppConfig.DEBUG) Log.d(TAG, "Notification set up"); if (AppConfig.DEBUG)
Log.d(TAG, "Notification set up");
} }
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@SuppressLint("NewApi")
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(final Context context, final Intent intent) {
int status = -1; AsyncTask<Void, Void, Void> handler = new AsyncTask<Void, Void, Void>() {
boolean successful = false;
int reason = 0;
if (AppConfig.DEBUG) Log.d(TAG, "Received 'Download Complete' - message.");
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
// get status
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor c = downloadManager.query(q);
if (c.moveToFirst()) {
status = c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS));
}
FeedFile download = requester.getFeedFile(downloadId);
if (download != null) {
if (status == DownloadManager.STATUS_SUCCESSFUL) {
if (download.getClass() == Feed.class) { @Override
handleCompletedFeedDownload(context, (Feed) download); protected Void doInBackground(Void... params) {
} else if (download.getClass() == FeedImage.class) { int status = -1;
handleCompletedImageDownload(context, boolean successful = false;
(FeedImage) download); int reason = 0;
} else if (download.getClass() == FeedMedia.class) { if (AppConfig.DEBUG)
handleCompletedFeedMediaDownload(context, Log.d(TAG, "Received 'Download Complete' - message.");
(FeedMedia) download); long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
// get status
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor c = downloadManager.query(q);
if (c.moveToFirst()) {
status = c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS));
} }
successful = true; FeedFile download = requester.getFeedFile(downloadId);
if (download != null) {
if (status == DownloadManager.STATUS_SUCCESSFUL) {
} else if (status == DownloadManager.STATUS_FAILED) { if (download.getClass() == Feed.class) {
reason = c.getInt(c handleCompletedFeedDownload(context,
.getColumnIndex(DownloadManager.COLUMN_REASON)); (Feed) download);
Log.e(TAG, "Download failed"); } else if (download.getClass() == FeedImage.class) {
Log.e(TAG, "reason code is " + reason); handleCompletedImageDownload(context,
successful = false; (FeedImage) download);
long statusId = saveDownloadStatus(new DownloadStatus( } else if (download.getClass() == FeedMedia.class) {
download, reason, successful)); handleCompletedFeedMediaDownload(context,
requester.removeDownload(download); (FeedMedia) download);
sendDownloadHandledIntent(download.getDownloadId(), }
statusId, false, 0); successful = true;
download.setDownloadId(0);
} else if (status == DownloadManager.STATUS_FAILED) {
reason = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.e(TAG, "Download failed");
Log.e(TAG, "reason code is " + reason);
successful = false;
long statusId = saveDownloadStatus(new DownloadStatus(
download, reason, successful));
requester.removeDownload(download);
sendDownloadHandledIntent(download.getDownloadId(),
statusId, false, 0);
download.setDownloadId(0);
}
queryDownloads();
c.close();
}
return null;
} }
queryDownloads(); };
c.close(); if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
handler.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
handler.execute();
} }
} }
@ -283,7 +306,8 @@ public class DownloadService extends Service {
} }
} }
if (createReport) { if (createReport) {
if (AppConfig.DEBUG) Log.d(TAG, "Creating report"); if (AppConfig.DEBUG)
Log.d(TAG, "Creating report");
int successfulDownloads = 0; int successfulDownloads = 0;
int failedDownloads = 0; int failedDownloads = 0;
for (DownloadStatus status : completedDownloads) { for (DownloadStatus status : completedDownloads) {
@ -314,7 +338,8 @@ public class DownloadService extends Service {
nm.notify(REPORT_ID, notification); nm.notify(REPORT_ID, notification);
} else { } else {
if (AppConfig.DEBUG) Log.d(TAG, "No report is created"); if (AppConfig.DEBUG)
Log.d(TAG, "No report is created");
} }
} }
@ -335,21 +360,24 @@ public class DownloadService extends Service {
/** Is called whenever a Feed is downloaded */ /** Is called whenever a Feed is downloaded */
private void handleCompletedFeedDownload(Context context, Feed feed) { private void handleCompletedFeedDownload(Context context, Feed feed) {
if (AppConfig.DEBUG) Log.d(TAG, "Handling completed Feed Download"); if (AppConfig.DEBUG)
Log.d(TAG, "Handling completed Feed Download");
syncExecutor.execute(new FeedSyncThread(feed, this)); syncExecutor.execute(new FeedSyncThread(feed, this));
} }
/** Is called whenever a Feed-Image is downloaded */ /** Is called whenever a Feed-Image is downloaded */
private void handleCompletedImageDownload(Context context, FeedImage image) { private void handleCompletedImageDownload(Context context, FeedImage image) {
if (AppConfig.DEBUG) Log.d(TAG, "Handling completed Image Download"); if (AppConfig.DEBUG)
Log.d(TAG, "Handling completed Image Download");
syncExecutor.execute(new ImageHandlerThread(image, this)); syncExecutor.execute(new ImageHandlerThread(image, this));
} }
/** Is called whenever a FeedMedia is downloaded. */ /** Is called whenever a FeedMedia is downloaded. */
private void handleCompletedFeedMediaDownload(Context context, private void handleCompletedFeedMediaDownload(Context context,
FeedMedia media) { FeedMedia media) {
if (AppConfig.DEBUG) Log.d(TAG, "Handling completed FeedMedia Download"); if (AppConfig.DEBUG)
Log.d(TAG, "Handling completed FeedMedia Download");
syncExecutor.execute(new MediaHandlerThread(media, this)); syncExecutor.execute(new MediaHandlerThread(media, this));
} }
@ -381,14 +409,16 @@ public class DownloadService extends Service {
try { try {
feed = handler.parseFeed(feed); feed = handler.parseFeed(feed);
if (AppConfig.DEBUG) Log.d(TAG, feed.getTitle() + " parsed"); if (AppConfig.DEBUG)
Log.d(TAG, feed.getTitle() + " parsed");
feed.setDownloadId(0); feed.setDownloadId(0);
// Save information of feed in DB // Save information of feed in DB
savedFeed = manager.updateFeed(service, feed); savedFeed = manager.updateFeed(service, feed);
// Download Feed Image if provided and not downloaded // Download Feed Image if provided and not downloaded
if (savedFeed.getImage().isDownloaded() == false) { if (savedFeed.getImage().isDownloaded() == false) {
if (AppConfig.DEBUG) Log.d(TAG, "Feed has image; Downloading...."); if (AppConfig.DEBUG)
Log.d(TAG, "Feed has image; Downloading....");
imageId = requester.downloadImage(service, feed.getImage()); imageId = requester.downloadImage(service, feed.getImage());
hasImage = true; hasImage = true;
} }
@ -431,9 +461,10 @@ public class DownloadService extends Service {
/** Delete files that aren't needed anymore */ /** Delete files that aren't needed anymore */
private void cleanup() { private void cleanup() {
if (new File(feed.getFile_url()).delete()) if (new File(feed.getFile_url()).delete())
if (AppConfig.DEBUG) Log.d(TAG, "Successfully deleted cache file."); if (AppConfig.DEBUG)
else Log.d(TAG, "Successfully deleted cache file.");
Log.e(TAG, "Failed to delete cache file."); else
Log.e(TAG, "Failed to delete cache file.");
feed.setFile_url(null); feed.setFile_url(null);
} }
@ -487,7 +518,8 @@ public class DownloadService extends Service {
e.printStackTrace(); e.printStackTrace();
} }
media.setDuration(mediaplayer.getDuration()); media.setDuration(mediaplayer.getDuration());
if (AppConfig.DEBUG) Log.d(TAG, "Duration of file is " + media.getDuration()); if (AppConfig.DEBUG)
Log.d(TAG, "Duration of file is " + media.getDuration());
mediaplayer.reset(); mediaplayer.reset();
long statusId = saveDownloadStatus(new DownloadStatus(media, 0, long statusId = saveDownloadStatus(new DownloadStatus(media, 0,
true)); true));