Reputation: 1
I am trying to develop a simple application for download using DownloadManager
but I need to do some changes, I want to download using ProgressbarDialog
so how to do.
class DownloadReceiver
if(downloader == null) return;
long completeId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
if(completeId == downloadTaskId){
Query query = new Query();
query.setFilterById(downloadTaskId);
Cursor cur = downloader.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
//Download the task has been completed, remove
new VersionPersistent(context).clear();
String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
File apkFile = new File(Uri.parse(uriString).getPath());
Intent installIntent = new Intent();
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setAction(Intent.ACTION_VIEW);
installIntent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
context.startActivity(installIntent);
} else {
Toast.makeText(context, R.string.download_failure, Toast.LENGTH_SHORT).show();
}
}
cur.close();
and also download and install
if ( latestVersion == null || !isNetworkActive() ) return;
downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Query query = new Query();
query.setFilterById(downloadTaskId);
Cursor cur = downloader.query(query);
// Download tasks already exists
if(cur.moveToNext()) return;
DownloadManager.Request task = new DownloadManager.Request(Uri.parse(latestVersion.targetUrl));
String apkName = extractName(latestVersion.targetUrl);
String title = String.format("%s - v%s", apkName,latestVersion.name);
task.setTitle(title);
task.setDescription(latestVersion.feature);
task.setVisibleInDownloadsUi(true);
task.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
task.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
downloadTaskId = downloader.enqueue(task);
Thanks :)
Upvotes: 0
Views: 737
Reputation: 24114
This is my working sample code. I use SeekBar instead of ProgressBar. Hope this help
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadmanager" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<LinearLayout
style="?android:buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<Button
android:id="@+id/buttonStartDownload"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="startDownload"
android:text="Start" />
<Button
android:id="@+id/buttonCancelDownload"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="cancelDownload"
android:text="Cancel" />
<Button
android:id="@+id/buttonViewDownloads"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="viewDownloads"
android:text="View" />
</LinearLayout>
</RelativeLayout>
MainActivity.java:
package com.example.downloadmanager;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private DownloadManager mDownloadManager;
private long mDownloadReference;
private TextView mTextView;
private SeekBar mSeekBar;
private static Cursor mCursor;
private static boolean mDownloading = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
mSeekBar = (SeekBar) findViewById(R.id.seekBar);
// Set filter to only when download is complete and register broadcast receiver
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, filter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void startDownload(View view) {
mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse("http://192.168.0.100/files/test.txt");
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
// Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
// Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("My Download");
// Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Android Data download using DownloadManager...");
// Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "test.txt");
// Enqueue a new download and same the referenceId
mDownloadReference = mDownloadManager.enqueue(request);
new Thread(new Runnable() {
@Override
public void run() {
mDownloading = true;
while (mDownloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(mDownloadReference);
mCursor = mDownloadManager.query(q);
if (mCursor != null && mCursor.getCount() > 0) {
mCursor.moveToFirst();
int bytes_downloaded = mCursor.getInt(mCursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
mDownloading = false;
}
final double dl_progress = ((bytes_downloaded * 100) / bytes_total);
runOnUiThread(new Runnable() {
@Override
public void run() {
mSeekBar.setProgress((int) dl_progress);
}
});
}
if (mCursor != null) {
mCursor.close();
}
}
}
}).start();
}
public void cancelDownload(View view) {
mDownloading = false;
if (mDownloadManager != null) {
mDownloadManager.remove(mDownloadReference);
}
mSeekBar.setProgress(0);
}
public void viewDownloads(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mDownloadReference == referenceId) {
Uri uri = mDownloadManager.getUriForDownloadedFile(mDownloadReference);
if (uri != null) {
String mimeType = mDownloadManager.getMimeTypeForDownloadedFile(mDownloadReference);
File file = new File(uri.getPath());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("FileName", file.getName());
jsonObject.put("FilePath", file.getAbsolutePath());
jsonObject.put("FileSize", file.length());
jsonObject.put("MimeType", mimeType);
String msg = "Download completed! \n\n" + jsonObject.toString(5);
mTextView.setText(msg);
} catch (JSONException e) {
mTextView.setText(e.getMessage());
}
}
}
}
};
}
Upvotes: 0
Reputation: 22955
USE this class to show progress bar , this will give you an idea for downloading an image.
DownloadImageTask.java
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** Reference to the view which should receive the image */
private final WeakReference imageRef;
public DownloadImageTask(ImageView imageView) {
imageRef = new WeakReference(imageView);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
@Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
URL url = new URL(params[0]);
// We open the connection
URLConnection conection = url.openConnection();
conection.connect();
input = new BufferedInputStream(url.openStream(), 8192);
// we convert the inputStream into bitmap
bitmap = BitmapFactory.decodeStream(input);
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
} else
Toast.makeText(DownloadImageActivity.this, "Error while downloading the image!", Toast.LENGTH_LONG).show();
}
}
}
give permission in AndroidMenifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Upvotes: 1
Reputation: 4032
Use Asynctask for this. Try this.
private class DownloadFileTask extends AsyncTask<String, Void, String> {
ProgressDialog pd;
@Override
protected String doInBackground(String... params) {
// Your File Download Code here
}
@Override
protected void onPostExecute(String result) {
pd.dismiss();
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(yourActivity.this);
pd.setMessage("Please Wait...");
pd.show();
}
@Override
protected void onProgressUpdate(Void... values) {}
}
}
Upvotes: 0
Reputation: 354
You should use DownloadManager's
DownloadManager.query(DownloadManager.Query)
This gives you a Cursor to browse the columns COLUMN_TOTAL_SIZE_BYTES (Total size of the download in bytes) and COLUMN_BYTES_DOWNLOADED_SO_FAR (Number of bytes download so far).
With this information, you'll have the details to update the ProgressBarDialog.
Upvotes: 0
Reputation: 1
you want using progressDialog, does that mean you don't need to download in the background ?
My solution is:
using AsyncTask
init the profressDialog before you call task.execute()
then show the dialog in onPreExecute
download file doInBackfround
update progess in onProgressUpdate
and dosomething you want when download complete in onPostExecute
you can learn AsyncTask
and HttpURLConnection
and IO Stream
Upvotes: 0