stand alone broadcast receiver for Download Manager - android

I have a BroadcastReceiver which listens for a download complete action so it opens a file when download completes.
My issue with this is that the user may download a file and then minimize the screen which then unregisters the BroadcastReceiver, so the file isn't opened automatically when download completes.
How can I set up a stand alone BroadcastReceiver so that the image is opened even when the app is stopped/destroyed. I can't figure out how to make it listen to a download complete action.
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadReference == referenceId) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(referenceId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
Intent intentpic = new Intent();
intentpic.setAction(android.content.Intent.ACTION_VIEW);
intentpic.setDataAndType(Uri.fromFile(getActivity().getExternalFilesDir("/update/asd.jpg")), "image/*");
startActivity(intentpic);
if(receiverRegistered) {
getActivity().unregisterReceiver(downloadReceiver);
}
}
}
cursor.close();
Log.i(TAG, "Downloading of data just finished");
}
}
};

You shouldn't start activities when your app is in background. It is okay that your receiver is unregistered when user leaves the app.
Instead, store the information that the image is downloaded and then check it when the app is resumed. I don't know your use case, but, for example you can store this information to SharedPreferences and check it when the app is resumed. Then you can decide whether to start a new activity or not.

Related

How to find name of file being downloaded using Download Manager

DownloadManager is a background service. I would like to get a list of files that are currently being downloaded using DownloadManager.
Say download process is launched in activity A and I open activity B. In activity B I would like to know which url/file is being downloaded. How to achieve this? If multiple files are being downloaded, then how can I get the list?
You can do something like below in your broadcast receiver to identify the files that ate downloaded. Replace YOUR_DM with your DownloadManager instance.
receiver_complete = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE){
Bundle extras = intent.getExtras();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
Cursor c = YOUR_DM.query(q);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// process download
title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
// get other required data by changing the constant passed to getColumnIndex
}
}
}
}
};

onReceive not being called when BroadcastReceiver is registered using LocalBroadcastManager

I've created a BroadcastReceiver to receive ACTION_DOWNLOAD_COMPLETE when my app starts downloading something using DownloadManager. As I want to capture ACTION_DOWNLOAD_COMPLETE only when downloading is started from my app, I've used LocalBroadcastManager.
But onReceiver is not being called at all. DownloadManager app shows that download is complete but onReceive is not triggered. When I use registerReceiver it works as expected. But this would let app being notified even if downloading is started by some other app. So LocalBroadcastManager is desired.
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadReceiver = new DownloadReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
if(FileHelper.isStorageAvailable()) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/image.jpg"));
downloadManager.enqueue(request);
}
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(downloadReceiver);
super.onPause();
}
DownloadReciever
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
Toast.makeText(context, title, Toast.LENGTH_SHORT).show();
}
}
}
}
It simply don't call onRecieve as it should. Point out if I'm doing something wrong here. Been stuck here for quite time now. I can't use registerReceiver as I need to track download complete action only if my app starts downloading.
As I want to capture ACTION_DOWNLOAD_COMPLETE only when downloading is started from my app, I've used LocalBroadcastManager.
That is not going to work. DownloadManager does the download in a separate process, and it will use a system broadcast. The only broadcasts that you can receive via LocalBraodcastManager are the ones that you broadcast via LocalBroadcastManager.

Receive download manager download complete intent and compare id - android

I am using download manager in my activity to download a file. I want to receive the ACTION_DOWNLOAD_COMPLETE intent using a broadcast receiver and match the id of the download request with the id in the intent set by download manager to check if it is the same download.
There are two options:
1) receive the intent in the activity by making a intent filter and registering a broadcast receiver. Problem here is that the broadcast receiver exists within the activity and gets destroyed with it. So if the download doesn't get completed before the activity is destroyed there is no way to receive the intent.
this.downloadId = manager.enqueue(request);
downloadID is compared with the EXTRA_DOWNLOAD_ID of the intent in onReceive method to check if it is the same download. downloadId variable is accessible inside the onReceive method.
2) receive the broadcast via manifest. Problem here is that the onReceive method does not have access to the downloadId variable set inside the activity. So I cannot check if the download is the one I need.
Am I doing it wrong? Basically I want to know if the download was completed successfully or not even if the activity/service where the download started is destroyed.
I hope my question is clear enough.
surely your first option is not good because you must do some work as soon as your download is completed so i suggest you use the second approach and store the downloadid in sharedpreferance or in a file and in onRecieve method check that by stored value. you can also use database but if you want to store just one variable (downloadid) in it, it is not a good idea because you must create table and ...
so let's see some code:
in your activity after saving your downloadid to a variable put it in a SharedPreferences file like:
SharedPreferences settings = getSharedPreferences("DownloadIDS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("savedDownloadIds", your download id);
editor.commit();
and in onReceive:
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences downloadids = context.getSharedPreferences("DownloadIDS", 0);
long savedDownloadIds = downloadids.getLong("savedDownloadIds", 0);
Bundle extras = intent.getExtras();
DownloadManager.Query q = new DownloadManager.Query();
Long downloaded_id = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
if(savedDownloadIds == downloaded_id ){ // so it is my file that has been completed
q.setFilterById(downloaded_id);
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = manager.query(q);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// do any thing here
}
}
c.close();
}
}
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

Android DownloadManager

I am using Android DownloadManager to download some file say of XMB if DownloadManager completes download it will send broadcast of action android.intent.action.DOWNLOAD_COMPLETE in normal scenario.
My question is what if the internet connection gets lost in between. Will it send any broadcast? Same case in between if server stops serving what DownloadManager does. Maybe its silly question, I have very small file so I am unable to test this scenario.
Could some one tell me what DownloadManager does in these kind of scenarios?
The broadcast will be sent. You need to check the status of DownloadManager to determine if it was successful. For example:
private DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
// handle data
} else if (DownloadManager.STATUS_FAILED == c.getInt(columnIndex)) {
// handle error
}
}
}
}
};
For a full example, see: this link. For ways to determine the reason of the failure, see this link.
Courtesy : Android DownloadManager Example
I register my receiver for DownloadManager.ACTION_DOWNLOAD_COMPLETE broadcast only. This is invoked only when the download is successfully completed
Follow this three steps
Create a BroadcastReceiver as shown in snippet below.Inside the receiver we just check if the received broadcast is for our download by matching the received download id with our enqueued download.
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadID == id) {
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
};
Once the BroadcastReceiver is created you can register for ACTION_DOWNLOAD_COMPLETE in the onCreate method of your activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
It is also important that you unregister the BroadcastReceiver in onDestroy. This ensures you only listen for this broadcast as long as the activity is active
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
}
Complete example here

BroadcastReceiver onReceive() getting called twice

In my app, I am using DownloadManager, for downloading PDF's, which notifies the application via a BroadcastReceiver once the download is completed. My problem is the onReceive() method of BroadcastReceiver is getting called twice. The code is as follows:
In my list adapter, a for loop is run for downloading the selected pdf's. The downloading code is written in another class as follows:
public static void downloadCheat(final SherlockFragmentActivity activity, final String cheatName, String pathOnServer){
Request request = new Request(
Uri.parse(ApplicationConstants.CHEAT_DOWNLOAD_SERVER_URL
+ "/" + pathOnServer + cheatName + ".pdf"));
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
request.setShowRunningNotification(true);
}
else {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
final DownloadManager dm = (DownloadManager) activity
.getSystemService(Context.DOWNLOAD_SERVICE);
final long enqueue = dm.enqueue(request);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
long i = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
System.out.println(i);
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
}
}
//create custom notification
}
}
};
activity.registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
I am trying to add notifications for each pdf download. This works perfectly with download managers own internal notification for HoneyComb and above versions but for GingerBread it does not work and hence I have to push my own custom notification. So I need to determine the exact time when the pdf is downloaded completely. As of now I am able to push my own custom notification but the notifications come twice for every pdf download (As onReceive() is getting twice for each pdf). Can anyone please explain why onReceive() is called twice(for every pdf). Is there any workaround for this? Also could someone please recommend how the broadcast receiver can be un-registered in my case here?The above code is not a part of Activity, so I am not sure how to unregister the receiver.
Thanks for stopping by and reading the post.
You normally register receivers onResume() and unregister in onPause(). Are you doing so?
I think I may have originally misunderstood what you were trying to do. You should be able to call unregisterReceiver from onReceive. Does this do what you want?
You said you are downloading two pdfs. I only see one Download Request in your method. So I assume what you did is to call that method twice. If that is true, you actually registered two receiver to receive the ACTION_DOWNLOAD_COMPLETE event.
You only need to register once in onCreate or onStart or some methods else. For notification purpose, you can use intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) to get the download id, the id is unique for each download. You can use this id to get the information about the downloaded file and make your file-specific notification.
This looks like the same bug that is described here:
https://code.google.com/p/android/issues/detail?id=18462

Categories

Resources