Local broadcast manager for downloading files - android

I'm creating a local broadcast receiver for notifying an activity when a download has started and finished. I have two classes, one is the DownloadFileFromURL class that i call to download certain file, and in it I've defined this:
Intent intent = new Intent("completeDownloadItem");
// You can also include some extra data.
intent.putExtra("completedItem", suraName);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
that in my opinion should send a broadcast to my DownloadManager class that has this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_manager);
LocalBroadcastManager.getInstance(this).registerReceiver(itemReceiver,
new IntentFilter("addDownloadItem"));
LocalBroadcastManager.getInstance(this).registerReceiver(
completeReceiever, new IntentFilter("completeDownloadItem"));
}
private BroadcastReceiver itemReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
Songs s = (Songs) intent.getSerializableExtra("newItems");
Log.d("receiver", "Got song: " + s.getTitle());
}
};
private BroadcastReceiver completeReceiever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("completedItem");
Log.d("receiver", "Downloaded: " + message);
}
};
Can any one tell me what am I missing, should I define local broadcast receiver in the manifest or something?
here is the DownloadFileFromURL class:
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog dialog;
private String reciterName, suraName;
private String file_url, filePath;
private MediaScannerConnection msc;
private DatabaseHelper db;
private int songNumber;
public DownloadFileFromURL(Context context, String reciterName,
String suraName, String fileURL, int songNumber) {
this.context = context;
this.songNumber = songNumber;
this.reciterName = reciterName;
this.suraName = suraName;
this.file_url = fileURL;
db = new DatabaseHelper(context);
}
protected void createDialog() {
// switch (id) {
// case progress_bar_type: // we set this to 0
dialog = new ProgressDialog(context);
// dialog.setMessage(context.getString(R.string.downloading) + " "
// + songName);
/*
* dialog.setIndeterminate(false); dialog.setMax(100);
*/
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(false);
dialog.show();
// default:
// return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// createDialog();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(file_url);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
File appDir = new File(Environment.getExternalStorageDirectory()
.getPath() + "/" + context.getString(R.string.app_name));
appDir.mkdirs();
File albumDir = new File(appDir.getPath().toString() + "/"
+ reciterName);
albumDir.mkdirs();
OutputStream output = new FileOutputStream(appDir + "/"
+ reciterName + "/" + suraName + ".mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// dialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
msc = new MediaScannerConnection(context,
new MediaScannerConnection.MediaScannerConnectionClient() {
#Override
public void onScanCompleted(String path, Uri uri) {
msc.disconnect();
}
#Override
public void onMediaScannerConnected() {
msc.scanFile(filePath, null);
}
});
if (!msc.isConnected()) {
}
// dialog.dismiss();
db.openDB();
db.addDownloaded(songNumber, reciterName);
db.closeDB();
Intent intent = new Intent("completeDownloadItem");
// You can also include some extra data.
intent.putExtra("completedItem", suraName);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Toast.makeText(context, "Sucessfully downloaded " + suraName,
Toast.LENGTH_SHORT).show();
}
}

No, local broadcast receivers don't need to be configured in the AndroidManifest.xml. I have to say that I am as well a bit puzzled why the notification does not work; have you debugged into the code and checked if the broadcast is actually send out and whether the receiver is registered properly?
If you cannot get it working (for whatever reason), consider using a library like EventBus for your inter-component communication needs. Personally I haven't used the LocalBroadcastManager in ages...

Related

Manage Queue in android with service

I have a activity with recycler-view, and each list item has a download button.inside button click event i manage make call for download-service.so how can i manage queue when user click more than one download button with custom notification update.
I have googled and tried some solutions are:
1.How to Manage Queue of Runnable Tasks in Android
2.how to handle a queue in android?? java
3.Best way to update Activity from a Queue
but doesn't find the correct way to implement queue with notification update.
Here is my DownloadService Code:
public class DownloadApkService extends Service {
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
String downloadLocation;
String appId = null;
String appLink = null;
String appName = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Queue", "queue");
appId = intent.getStringExtra(Constants.COM_APP_ID);
appLink = intent.getStringExtra(Constants.COM_APP_LINK);
appName = intent.getStringExtra(Constants.COM_APP_NAME);
Thread thread=new Thread(new MyThread(startId));
thread.start();
return START_STICKY;
}
final class MyThread implements Runnable {
int service_id;
MyThread(int service_id) {
this.service_id = service_id;
}
#Override
public void run() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
.setSmallIcon(R.drawable.ic_list_app_icon)
.setContentTitle(appName).setProgress(0, 0, true)
.setContentText("Downloading APK")
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
downloadApk();
}
}
private void downloadApk() {
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
File sourceFile = new File(downloadLocation);
if (sourceFile.exists()) {
sourceFile.delete();
}
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
sendBroadcast(intentResponse);
new DownloadFileFromURL().execute(appLink);
}
public void installApk(Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
DownloadApkService.this.startActivity(install);
}
/**
* Background Async Task to download file
*/
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
Log.e("ULR", f_url[0]);
URL url = new URL(f_url[0].trim());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
Log.e("Length", lenghtOfFile + "");
// download the file
InputStream input = connection.getInputStream();
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
// Output stream
FileOutputStream output = new FileOutputStream(downloadLocation);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getStackTrace().toString());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
sendBroadcast(intentResponse);
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
notificationManager.cancel(0);
installApk(Uri.fromFile(new File(downloadLocation)));
}
}
}
any help would be appriciated...
Finally got answer for my own question.
I managed it with Queue class that is in java.util package.
The code i have been used is below:
public class DownloadApkService extends Service {
private NotificationManager notificationManager = null;
String downloadLocation;
String appId = null;
String appLink = null;
String appName = null;
String isApkFromServer = null;
public boolean isDownloading = false;
public static Queue<QueueData> downloadQueue = new LinkedList<>();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isDownloading) {
QueueData queueData = new QueueData();
queueData.setAppId(intent.getStringExtra(Constants.COM_APP_ID));
queueData.setAppLink(intent.getStringExtra(Constants.COM_APP_LINK));
queueData.setIsApkFromServer(intent.getStringExtra(Constants.COM_APK_FROM_SERVER));
queueData.setAppName(intent.getStringExtra(Constants.COM_APP_NAME));
downloadQueue.add(queueData);
Intent intentQueueingApk = new Intent();
intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
sendBroadcast(intentQueueingApk);
return START_NOT_STICKY;
} else {
appId = intent.getStringExtra(Constants.COM_APP_ID);
appLink = intent.getStringExtra(Constants.COM_APP_LINK);
appName = intent.getStringExtra(Constants.COM_APP_NAME);
isApkFromServer = intent.getStringExtra(Constants.COM_APK_FROM_SERVER);
}
Thread thread = new Thread(new MyThread());
thread.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (notificationManager != null) {
notificationManager.cancel(0);
}
}
class MyThread implements Runnable {
MyThread() {
}
#Override
public void run() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(appName).setProgress(0, 0, true)
.setContentText(getResources().getText(R.string.downloading_notification))
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
new DownloadFileFromURL().execute(appLink);
}
}
public void installApk(Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
DownloadApkService.this.startActivity(install);
}
/**
* Background Async Task to download file
*/
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
isDownloading = true;
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
sendBroadcast(intentResponse);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
HttpURLConnection connection=null;
try {
String link=f_url[0].replace(" ","%20");
URL url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
int lenghtOfFile = connection.getContentLength();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
File sourceFile = new File(downloadLocation);
if (sourceFile.exists()) {
sourceFile.delete();
}
// Output stream
FileOutputStream output = new FileOutputStream(downloadLocation);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
return "fail";
}finally {
if(connection != null)
connection.disconnect();
}
return "success";
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
sendBroadcast(intentResponse);
Intent intentQueueingApk = new Intent();
intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
sendBroadcast(intentQueueingApk);
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
notificationManager.cancel(0);
if (file_url.equals("success")) {
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_COMPLETE);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
sendBroadcast(intentResponse);
isDownloading = false;
if (isApkFromServer!=null && isApkFromServer.equals("0")) {
Intent intent = new Intent(DownloadApkService.this, UploadApkService.class);
intent.putExtra(Constants.COM_APP_ID, mAppDetails.getId());
intent.putExtra(Constants.COM_APK_FILE_PATH, downloadLocation);
startService(intent);
}
installApk(Uri.fromFile(new File(downloadLocation)));
} else if (file_url.equals("fail")) {
isDownloading = false;
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_FAILED);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
sendBroadcast(intentResponse);
}
if (/*isDownloading &&*/ !downloadQueue.isEmpty()) {
QueueData queueData = downloadQueue.poll();
appId = queueData.getAppId();
appLink = queueData.getAppLink();
appName = queueData.getAppName();
isApkFromServer = queueData.getIsApkFromServer();
Thread thread = new Thread(new MyThread());
thread.start();
}
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
if (notificationManager != null)
notificationManager.cancel(0);
}
}
I hope it's going to be helpful for someone.

How to change this class to download audio file?

I have this class that downloads an image from a server and that I carry it on my main activity
public class imgDownloader extends AsyncTask<Void, Integer, Void> {
private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
/*--- constructor ---*/
public ImageDownloader(String url, ProgressBar pb, Button save,
ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
this.url = url;
this.pb = pb;
this.save = save;
this.c = c;
this.img = img;
this.percent = percent;
this.bmp = bmp;
this.listener = listener;
}
/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity.
* Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {
void onImageDownloaded(Bitmap bmp);
}
#Override
protected void onPreExecute() {
//progress = 0;
//pb.setVisibility(View.VISIBLE);
//percent.setVisibility(View.VISIBLE);
//Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();
Log.d("Script", "//" + "starting download");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
bmp = getBitmapFromURL(url);
/*
while (progress < 10) {
progress += 1;
publishProgress(progress);
SystemClock.sleep(200);
}
*/
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
/*--- show download progress on main UI thread---*/
// pb.setProgress(values[0]);
// percent.setText(values[0] + "%");
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onImageDownloaded(bmp);
}
img.setImageBitmap(bmp);
//save.setEnabled(true);
//Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();
Log.d("Script", "//" + "download complete");
super.onPostExecute(result);
}
}
I need instead of downloading an image to download a mp3 audio file and use the call of my NOTIFICATION
This is where I use some flags and use an audio that is in my raw pasta.
noti.sound = Uri.parse("android.resource://"
+ _context.getPackageName() + "/" + R.raw.galo);
noti.flags |= Notification.FLAG_NO_CLEAR;
noti.defaults |= Notification.DEFAULT_LIGHTS;
noti.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
noti.priority = Notification.PRIORITY_MAX;
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, noti);
Here I need to use the same class adapted upon to download the audio, but do not know how I can do this. Download the audio file and let the SDCARD is out of the question.
noti.sound = Uri.parse("android.resource://" + _context.getPackageName() + "/" + R.raw.galo);
You can try this class to download file
//to call
new DownloadFileFromURL().execute("download_url");
//Class to download file
class DownloadFileFromURL extends AsyncTask<String, String, String>
{
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url)
{
int count;
try
{
//file name with extension
File file=new File("/directory/file.mp3");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
pDialog.dismiss();
}
}

if turn off wifi,cancel download [android]

in the following code I used of onpause and onstop and ondestroy but it is useless and when turn off wifi by user save incomplete file but I want when turn off wifi by user,canceled download.
what can i do?
what should I add in the code?
my code:
public class DoaMatn1 extends Activity implements OnClickListener {
// .
// .
// .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doamatn);
// .
// .
// .
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-tavasol.mp3");
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnplaydoa :
// .
// .
// .
case R.id.btndowndoa :
if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-tavasol.mp3").exists())
downloadTask = (DownloadFileFromURL) new DownloadFileFromURL().execute(file_url);
}}
#Override
protected void onStop() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onStop();
}
#Override
protected void onPause() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onPause();
}
#Override
protected void onDestroy() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onDestroy();
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onCancelled() {
File file= new File("/sdcard/EBKH/basem-tavasol.mp3");
file.delete();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream("/sdcard/EBKH/basem-tavasol.mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}}
Taken from this question...
Register a broadcast receiver:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
and receive:
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if (!connected) {
// Stop the download.
}
}
}
This method will detect a change in wifi and if the change is that the wifi is not connected, cancel the download.

Android IllegalArgumentException for dismissDialog

I have used following code for download some files from our internet.
public class SplashDownload extends Activity {
public static final int PROGRESS_DIALOG = 0;
private ProgressDialog mProgressDialog;
private WordDataHelper wordDataHelper;
private ExtraDataHelper extraDataHelper;
// put your file path here
private String filePath = "http://test.com/Assets/";
// put your filename here
private String fileName;
// put your download directory name here
private String downloadDir;
private int wordCounter = 0, extraCounter = 0, counter = 1;
private boolean wordDLOn = true;
private int totalFileNo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashdllayout);
getDownloadList();
}
private void goForward() {
Intent intent = new Intent().setClass(this, LangH.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
private void doNext() {
if (wordDLOn) {
System.out.print("wordDetails update: "
+ wordDetails[wordCounter - 1][0]
+ extraDetails[extraCounter][0] + fileName);
wordDataHelper.updateDLStat(Long
.valueOf(wordDetails[wordCounter - 1][0]));
} else {
System.out.print("extraDetails update: "
+ extraDetails[extraCounter - 1][0] + fileName);
extraDataHelper.updateDLStat(Long
.valueOf(extraDetails[extraCounter - 1][0]));
}
if (wordCounter < wordDetails.length) {
System.out.print("wordCounter: " + wordCounter + "/"
+ wordDetails.length);
startDownload(wordDetails[wordCounter][1]);
wordCounter++;
} else if (extraCounter < extraDetails.length) {
wordDLOn = false;
downloadDir = "LanH/extras";
System.out.print("extraCounter: " + extraCounter + "/"
+ extraDetails.length);
startDownload(extraDetails[extraCounter][1]);
extraCounter++;
} else {
goForward();
}
}
private void getDownloadList() {
// lessons download..........
String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
downloadDir = "LanH/words";
String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};
totalFileNo = extraDetails.length + wordDetails.length;
if (wordDetails.length != 0) {
startDownload(wordDetails[wordCounter]);
wordCounter++;
} else if (extraDetails.length != 0) {
wordDLOn = false;
startDownload(extraDetails[extraCounter]);
extraCounter++;
} else {
goForward();
}
}
private void startDownload(String dlFilename) {
// tv = (TextView) findViewById(R.id.tv1);
fileName = dlFilename;
System.out.print("fileName: " + fileName);
File dir = new File(android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/"
+ downloadDir);
// creates the directory if it doesn't exists
if (dir.exists() == false) {
dir.mkdirs();
}
dir = null;
if (checkNet()) {
if (checkExternalMedia() == true) {
String url = filePath + fileName;
new DownloadFileAsync().execute(url, fileName);
mProgressDialog.setMessage("Downloading file.." + fileName);
} else {
Toast.makeText(getApplicationContext(),
"External Media is NOT readable/writable",
Toast.LENGTH_SHORT).show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
/** Method to check whether external media available and writable. */
private boolean checkExternalMedia() {
boolean stat;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
stat = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
stat = false;
} else {
// Can't read or write
stat = false;
}
return stat;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.." + fileName);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS_DIALOG);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
android.os.Environment.getExternalStorageDirectory()
+ "/" + downloadDir + "/" + aurl[1]);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("DOWNLOAD_TEST", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(PROGRESS_DIALOG);
// tv.append("\n\nFile Download Complete!");
// Button btn = (Button) findViewById(R.id.btn1);
// btn.setVisibility(View.GONE);
// you can call a second intent here to redirect to another screen
doNext();
}
}
private boolean checkNet() {
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// we are connected to a network
connected = true;
} else
connected = false;
return connected;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
The process is running fine. It is reported following crash report:
java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
What is the problem in my code? Is isShowing() check before dismissDialog will solve the prob?
Does your progress dialog actually show up?
Instead of dismissing it you could try using removeDialog(PROGRESS_DIALOG); to have it cleaned up.
See if this thread helps - AlerDialog is not created - java.lang.IllegalArgumentException: Activity#onCreateDialog did not create a dialog for id X
When you do the
mProgressDialog.show();
during
protected Dialog onCreateDialog(int id)
you already set the ID for the Dialog to some random or null value.
So when you call to dismiss it, the Application thinks you are crazy.

Activity with ProgressBar -> Service -> AsyncTask for downloading - but how to update the progress?

this is the current state/situation: I have an Activity which binds a Service which creates AsyncTasks which downloads various web resources. That works well, but of course the ProgressBar shows nothing.
Previously i had an Activity which created an AsyncTask which downloaded some stuff. The AsyncTask got the View which holds the ProgressBar. So i could update the progress using onProgressUpdate and publishProgress. Obviously this doesn't work any longer because I have no reference to the ProgressBar.
So, do you have any idea on how to update the progress?
Thanks in advance.
Very nice explained indeed just missing the example :)
I went throw it and here it is.
public class Detail extends Activity {
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
mProgressDialog.setProgress(intent.getFlags());
}
}
};
// Flag if receiver is registered
private boolean mReceiversRegistered = false;
// Define a handler and a broadcast receiver
private final Handler mHandler = new Handler();
#Override
protected void onResume() {
super.onResume();
// Register Sync Recievers
IntentFilter intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
mReceiversRegistered = true;
}
#Override
public void onPause() {
super.onPause();
// Make sure you unregister your receivers when you pause your activity
if(mReceiversRegistered) {
unregisterReceiver(mIntentReceiver);
mReceiversRegistered = false;
}
}
}
public class DownloadService extends Service {
private static final String CLASS_NAME = DownloadService.class.getSimpleName();
private List<Download> downloads = new ArrayList<Download>();
private int currentPosition;
public static final String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
private Context ctx;
#Override
public IBinder onBind(Intent arg0) {
ctx = getApplicationContext();
return mBinder;
}
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... _url) {
Log.d(Constants.LOG_TAG, CLASS_NAME + " Start the background GetNewsTask \nURL :" + _url[0]);
int count;
File finalFile = new File(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
try {
if (!finalFile.exists()) {
Log.i(Constants.LOG_TAG, CLASS_NAME + " Donwloading apk from the Web");
URL url = new URL(_url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
File dir = new File(sdcardPath + Constants.APK_LOCAL_PATH);
if (!dir.exists())
dir.mkdirs();
OutputStream output = new FileOutputStream(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
Log.i(Constants.LOG_TAG, CLASS_NAME + " Apk in SDcard");
publishProgress(100);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
Intent i = new Intent();
i.setAction(CUSTOM_INTENT);
i.setFlags(progress[0]);
ctx.sendBroadcast(i);
}
}
private String splitName(String url) {
String[] output = url.split("/");
return output[output.length - 1];
}
public static final String CUSTOM_INTENT = "es.tempos21.sync.client.ProgressReceiver";
private final IDownloadService.Stub mBinder = new IDownloadService.Stub() {
public void downloadAsynFile(String url) throws DeadObjectException {
try {
DownloadFile d = new DownloadFile();
d.execute(url);
} catch (Exception e) {
Log.e(Constants.LOG_TAG, CLASS_NAME + " " +e.getMessage()); }
}
}
};
interface IDownloadService {
void downloadAsynFile(String url);
}
Have the Service notify the then-running Activity about the progress from onProgressUpdate(). That could be via a broadcast Intent, or via a callback object registered by the Activity (and unregistered when the Activity is destroyed, such as on a screen rotation).
You can show progress just as easily via a Toast, which obviates all of the UI concerns:
public class foo extends Service {
private Toast toast;
#SuppressLint("ShowToast")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
ctxt = getApplicationContext();
toast = Toast.makeText(ctxt, "", Toast.LENGTH_SHORT);
...
}
public void functionCalledByYourAsyncWithUpdates(String progress){
toast.setText (progress);
toast.show;
}
}

Categories

Resources