public class MainActivity extends AppCompatActivity implements View.OnClickListener {
DownloadManager downloadManager;
String _URL = "your URL";
long refer;
BroadcastReceiver downloadcomplete;
BroadcastReceiver notificationClick;
Button btnDownload;
public void startdownload() {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(_URL);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("My download").setTitle("Notification Title");
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "your filename");
request.setVisibleInDownloadsUi(true);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
refer = downloadManager.enqueue(request);
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);
notificationClick = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
long[] references = intent.getLongArrayExtra(extraID);
for (long r : references) {
if (r == refer) {
// do something with download file}
}
}
};
registerReceiver(notificationClick, filter);
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
downloadcomplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long r = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (refer == r) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(r);
Cursor cursor = downloadManager.query(query);
cursor.moveToFirst();
//get status of the download
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
String saveFilePath = cursor.getString(filenameIndex);
int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cursor.getInt(columnReason);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
Toast.makeText(getApplicationContext(), "STATUS_SUCCESSFUL", Toast.LENGTH_SHORT).show();
break;
case DownloadManager.STATUS_FAILED:
// do somethingbreak;
case DownloadManager.STATUS_PAUSED:
// do somethingbreak;
case DownloadManager.STATUS_PENDING:
// do somethingbreak;
case DownloadManager.STATUS_RUNNING:
// do somethingbreak;
}
}
}
};
registerReceiver(downloadcomplete, intentFilter);
}
@Override
No comments:
Post a Comment