DownloadService no longer shows its notifications

This commit is contained in:
daniel oeh 2012-06-15 17:54:42 +02:00
parent a6df2fa2e4
commit 95a7a11fa3
3 changed files with 113 additions and 64 deletions

View File

@ -9,6 +9,7 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="10" /> <uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
<application <application
android:icon="@drawable/ic_launcher" android:icon="@drawable/ic_launcher"

View File

@ -26,6 +26,7 @@ import android.media.MediaPlayer;
import android.os.IBinder; import android.os.IBinder;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat;
@ -47,6 +48,9 @@ public class DownloadService extends Service {
private int NOTIFICATION_ID = 2; private int NOTIFICATION_ID = 2;
/** Needed to determine the duration of a media file */ /** Needed to determine the duration of a media file */
private MediaPlayer mediaplayer; private MediaPlayer mediaplayer;
private DownloadManager downloadManager;
private volatile boolean shutdownInitiated = false;
// Objects for communication // Objects for communication
private final Messenger mMessenger = new Messenger(new IncomingHandler()); private final Messenger mMessenger = new Messenger(new IncomingHandler());
@ -62,6 +66,7 @@ public class DownloadService extends Service {
manager = FeedManager.getInstance(); manager = FeedManager.getInstance();
requester = DownloadRequester.getInstance(); requester = DownloadRequester.getInstance();
mediaplayer = new MediaPlayer(); mediaplayer = new MediaPlayer();
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
setupNotification(); setupNotification();
} }
@ -75,6 +80,7 @@ public class DownloadService extends Service {
Log.d(TAG, "Service shutting down"); Log.d(TAG, "Service shutting down");
sendBroadcast(new Intent(ACTION_FEED_SYNC_COMPLETED)); sendBroadcast(new Intent(ACTION_FEED_SYNC_COMPLETED));
mediaplayer.release(); mediaplayer.release();
unregisterReceiver(downloadReceiver);
} }
private IntentFilter createIntentFilter() { private IntentFilter createIntentFilter() {
@ -116,8 +122,9 @@ public class DownloadService extends Service {
R.drawable.stat_notify_sync_noanim); R.drawable.stat_notify_sync_noanim);
notificationBuilder = new NotificationCompat.Builder(this) notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Downloading Podcast data") .setContentTitle("Downloading Podcast data")
.setContentText(requester.getNumberOfDownloads() + " Downloads left").setOngoing(true) .setContentText(
.setContentIntent(pIntent).setLargeIcon(icon) requester.getNumberOfDownloads() + " Downloads left")
.setOngoing(true).setContentIntent(pIntent).setLargeIcon(icon)
.setSmallIcon(R.drawable.stat_notify_sync_noanim); .setSmallIcon(R.drawable.stat_notify_sync_noanim);
startForeground(NOTIFICATION_ID, notificationBuilder.getNotification()); startForeground(NOTIFICATION_ID, notificationBuilder.getNotification());
@ -127,31 +134,52 @@ public class DownloadService extends Service {
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
int status = -1;
Log.d(TAG, "Received 'Download Complete' - message."); Log.d(TAG, "Received 'Download Complete' - message.");
long downloadId = intent.getLongExtra( long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0); DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Feed feed = requester.getFeed(downloadId); // get status
if (feed != null) { DownloadManager.Query q = new DownloadManager.Query();
handleCompletedFeedDownload(context, feed); q.setFilterById(downloadId);
} else { Cursor c = downloadManager.query(q);
FeedImage image = requester.getFeedImage(downloadId); if (c.moveToFirst()) {
if (image != null) { status = c.getInt(c
handleCompletedImageDownload(context, image); .getColumnIndex(DownloadManager.COLUMN_STATUS));
}
if (status == DownloadManager.STATUS_SUCCESSFUL) {
Feed feed = requester.getFeed(downloadId);
if (feed != null) {
handleCompletedFeedDownload(context, feed);
} else { } else {
FeedMedia media = requester.getFeedMedia(downloadId); FeedImage image = requester.getFeedImage(downloadId);
if (media != null) { if (image != null) {
handleCompletedFeedMediaDownload(context, media); handleCompletedImageDownload(context, image);
} else {
FeedMedia media = requester.getFeedMedia(downloadId);
if (media != null) {
handleCompletedFeedMediaDownload(context, media);
}
} }
} }
queryDownloads();
} else if (status == DownloadManager.STATUS_FAILED) {
int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.d(TAG, "reason code is " + reason);
} }
queryDownloads();
c.close();
} }
}; };
/** Check if there's something else to download, otherwise stop */ /** Check if there's something else to download, otherwise stop */
private void queryDownloads() { private synchronized void queryDownloads() {
if (requester.getNumberOfDownloads() == 0) { if (!shutdownInitiated && requester.getNumberOfDownloads() == 0) {
unregisterReceiver(downloadReceiver); shutdownInitiated = true;
initiateShutdown(); initiateShutdown();
} }
} }

View File

@ -25,6 +25,7 @@ import android.webkit.URLUtil;
public class DownloadRequester { public class DownloadRequester {
private static final String TAG = "DownloadRequester"; private static final String TAG = "DownloadRequester";
private static final int currentApi = android.os.Build.VERSION.SDK_INT;
public static String EXTRA_DOWNLOAD_ID = "extra.de.podfetcher.storage.download_id"; public static String EXTRA_DOWNLOAD_ID = "extra.de.podfetcher.storage.download_id";
public static String EXTRA_ITEM_ID = "extra.de.podfetcher.storage.item_id"; public static String EXTRA_ITEM_ID = "extra.de.podfetcher.storage.item_id";
@ -32,21 +33,20 @@ public class DownloadRequester {
public static String ACTION_FEED_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.feed_download_completed"; public static String ACTION_FEED_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.feed_download_completed";
public static String ACTION_MEDIA_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.media_download_completed"; public static String ACTION_MEDIA_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.media_download_completed";
public static String ACTION_IMAGE_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.image_download_completed"; public static String ACTION_IMAGE_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.image_download_completed";
private static boolean STORE_ON_SD = true; private static boolean STORE_ON_SD = true;
public static String IMAGE_DOWNLOADPATH = "images/"; public static String IMAGE_DOWNLOADPATH = "images/";
public static String FEED_DOWNLOADPATH = "cache/"; public static String FEED_DOWNLOADPATH = "cache/";
public static String MEDIA_DOWNLOADPATH = "media/"; public static String MEDIA_DOWNLOADPATH = "media/";
private static DownloadRequester downloader; private static DownloadRequester downloader;
private DownloadManager manager; private DownloadManager manager;
public ArrayList<FeedFile> feeds; public ArrayList<FeedFile> feeds;
public ArrayList<FeedFile> images; public ArrayList<FeedFile> images;
public ArrayList<FeedFile> media; public ArrayList<FeedFile> media;
private DownloadRequester(){ private DownloadRequester() {
feeds = new ArrayList<FeedFile>(); feeds = new ArrayList<FeedFile>();
images = new ArrayList<FeedFile>(); images = new ArrayList<FeedFile>();
media = new ArrayList<FeedFile>(); media = new ArrayList<FeedFile>();
@ -54,54 +54,66 @@ public class DownloadRequester {
} }
public static DownloadRequester getInstance() { public static DownloadRequester getInstance() {
if(downloader == null) { if (downloader == null) {
downloader = new DownloadRequester(); downloader = new DownloadRequester();
} }
return downloader; return downloader;
} }
private long download(Context context, ArrayList<FeedFile> type, FeedFile item, File dest, boolean visibleInUI) { private long download(Context context, ArrayList<FeedFile> type,
Log.d(TAG, "Requesting download of url "+ item.getDownload_url()); FeedFile item, File dest) {
Log.d(TAG, "Requesting download of url " + item.getDownload_url());
type.add(item); type.add(item);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(item.getDownload_url())); DownloadManager.Request request = new DownloadManager.Request(
//request.allowScanningByMediaScanner(); Uri.parse(item.getDownload_url()))
.setDestinationUri(Uri.fromFile(dest));
request.setDestinationUri(Uri.fromFile(dest)); Log.d(TAG, "Version is " + currentApi);
request.setVisibleInDownloadsUi(visibleInUI); if (currentApi >= 11) {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
} else {
request.setVisibleInDownloadsUi(false);
request.setShowRunningNotification(false);
}
// TODO Set Allowed Network Types // TODO Set Allowed Network Types
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager manager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
context.startService(new Intent(context, DownloadService.class)); context.startService(new Intent(context, DownloadService.class));
long downloadId = manager.enqueue(request); long downloadId = manager.enqueue(request);
item.setDownloadId(downloadId); item.setDownloadId(downloadId);
item.setFile_url(dest.toString()); item.setFile_url(dest.toString());
return downloadId; return downloadId;
} }
public long downloadFeed(Context context, Feed feed) { public long downloadFeed(Context context, Feed feed) {
return download(context, feeds, feed, return download(context, feeds, feed, new File(
new File(getFeedfilePath(context), getFeedfileName(feed)), getFeedfilePath(context), getFeedfileName(feed)));
true);
} }
public long downloadImage(Context context, FeedImage image) { public long downloadImage(Context context, FeedImage image) {
return download(context, images, image, return download(context, images, image, new File(
new File(getImagefilePath(context), getImagefileName(image)), getImagefilePath(context), getImagefileName(image)));
true);
} }
public long downloadMedia(Context context, FeedMedia feedmedia) { public long downloadMedia(Context context, FeedMedia feedmedia) {
return download(context, media, feedmedia, return download(context, media, feedmedia,
new File(getMediafilePath(context, feedmedia), getMediafilename(feedmedia)), new File(getMediafilePath(context, feedmedia),
true); getMediafilename(feedmedia)));
} }
/** Cancels a running download. /**
* @param context A context needed to get the DownloadManager service * Cancels a running download.
* @param id ID of the download to cancel *
* @param context
* A context needed to get the DownloadManager service
* @param id
* ID of the download to cancel
* */ * */
public void cancelDownload(final Context context, final long id) { public void cancelDownload(final Context context, final long id) {
Log.d(TAG, "Cancelling download with id " + id); Log.d(TAG, "Cancelling download with id " + id);
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager manager = (DownloadManager) context
int removed = manager.remove(id); .getSystemService(Context.DOWNLOAD_SERVICE);
int removed = manager.remove(id);
if (removed > 0) { if (removed > 0) {
// Delete downloads in lists // Delete downloads in lists
Feed feed = getFeed(id); Feed feed = getFeed(id);
@ -123,8 +135,8 @@ public class DownloadRequester {
/** Get a Feed by its download id */ /** Get a Feed by its download id */
public Feed getFeed(long id) { public Feed getFeed(long id) {
for(FeedFile f: feeds) { for (FeedFile f : feeds) {
if(f.getDownloadId() == id) { if (f.getDownloadId() == id) {
return (Feed) f; return (Feed) f;
} }
} }
@ -133,19 +145,18 @@ public class DownloadRequester {
/** Get a FeedImage by its download id */ /** Get a FeedImage by its download id */
public FeedImage getFeedImage(long id) { public FeedImage getFeedImage(long id) {
for(FeedFile f: images) { for (FeedFile f : images) {
if(f.getDownloadId() == id) { if (f.getDownloadId() == id) {
return (FeedImage) f; return (FeedImage) f;
} }
} }
return null; return null;
} }
/** Get media by its download id */ /** Get media by its download id */
public FeedMedia getFeedMedia(long id) { public FeedMedia getFeedMedia(long id) {
for(FeedFile f: media) { for (FeedFile f : media) {
if(f.getDownloadId() == id) { if (f.getDownloadId() == id) {
return (FeedMedia) f; return (FeedMedia) f;
} }
} }
@ -153,7 +164,7 @@ public class DownloadRequester {
} }
public void removeFeed(Feed f) { public void removeFeed(Feed f) {
feeds.remove(f); feeds.remove(f);
} }
public void removeFeedMedia(FeedMedia m) { public void removeFeedMedia(FeedMedia m) {
@ -164,9 +175,9 @@ public class DownloadRequester {
images.remove(fi); images.remove(fi);
} }
public ArrayList<FeedFile> getMediaDownloads() { public ArrayList<FeedFile> getMediaDownloads() {
return media; return media;
} }
/** Get the number of uncompleted Downloads */ /** Get the number of uncompleted Downloads */
public int getNumberOfDownloads() { public int getNumberOfDownloads() {
@ -178,7 +189,7 @@ public class DownloadRequester {
} }
public String getFeedfilePath(Context context) { public String getFeedfilePath(Context context) {
return context.getExternalFilesDir(FEED_DOWNLOADPATH).toString() + "/"; return context.getExternalFilesDir(FEED_DOWNLOADPATH).toString() + "/";
} }
public String getFeedfileName(Feed feed) { public String getFeedfileName(Feed feed) {
@ -194,12 +205,16 @@ public class DownloadRequester {
} }
public String getMediafilePath(Context context, FeedMedia media) { public String getMediafilePath(Context context, FeedMedia media) {
return context.getExternalFilesDir(MEDIA_DOWNLOADPATH return context
+ media.getItem().getFeed().getTitle() + "/").toString(); .getExternalFilesDir(
MEDIA_DOWNLOADPATH
+ media.getItem().getFeed().getTitle() + "/")
.toString();
} }
public String getMediafilename(FeedMedia media) { public String getMediafilename(FeedMedia media) {
return URLUtil.guessFileName(media.getDownload_url(), null, media.getMime_type()); return URLUtil.guessFileName(media.getDownload_url(), null,
media.getMime_type());
} }
public boolean isDownloaded(Feed feed) { public boolean isDownloaded(Feed feed) {
@ -226,7 +241,10 @@ public class DownloadRequester {
return m.getFile_url() != null && media.contains(m); return m.getFile_url() != null && media.contains(m);
} }
/* ------------ Methods for communicating with the DownloadService ------------- */ /*
* ------------ Methods for communicating with the DownloadService
* -------------
*/
private Messenger mService = null; private Messenger mService = null;
boolean mIsBound; boolean mIsBound;
@ -235,11 +253,13 @@ public class DownloadRequester {
mService = new Messenger(service); mService = new Messenger(service);
try { try {
Message msg = Message.obtain(null, DownloadService.MSG_QUERY_DOWNLOADS_LEFT); Message msg = Message.obtain(null,
DownloadService.MSG_QUERY_DOWNLOADS_LEFT);
Log.d(TAG, "Sending message to DownloadService."); Log.d(TAG, "Sending message to DownloadService.");
mService.send(msg); mService.send(msg);
} catch(RemoteException e) { } catch (RemoteException e) {
Log.e(TAG, "An Exception happened while communication with the DownloadService"); Log.e(TAG,
"An Exception happened while communication with the DownloadService");
} }
} }
@ -249,10 +269,10 @@ public class DownloadRequester {
} }
}; };
/** Notifies the DownloadService to check if there are any Downloads left */ /** Notifies the DownloadService to check if there are any Downloads left */
public void notifyDownloadService(Context context) { public void notifyDownloadService(Context context) {
context.bindService(new Intent(context, DownloadService.class), mConnection, Context.BIND_AUTO_CREATE); context.bindService(new Intent(context, DownloadService.class),
mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true; mIsBound = true;
context.unbindService(mConnection); context.unbindService(mConnection);
mIsBound = false; mIsBound = false;