Someone helps me out Pls
I wanted to implement a notification builder in my AsyncTask method for downloading files from the server. Notification that contains progress bar with incrementing base on file length, show download percentage and how many MB remain, with pause and resume, I try it but still notification not showing while downloading is doing in the background there is my code:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#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);
String folder = "/data/data/" + getPackageName() + "/files/";
File directory = new File(folder);
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream output = new FileOutputStream(folder + getIntent().getStringExtra("title") + ".mp4");
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);
String type = "downloads";
Update(type);
View layout = getLayoutInflater().inflate(R.layout.toast_custom, findViewById(R.id.custom_toast_layout_id));
TextView text = layout.findViewById(R.id.text);
text.setText(getIntent().getStringExtra("title") + " - Downloaded Successfully!");
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
Where is the code to show Notification and which android version os are you using ?
Related
I work with a RecyclerView that looks like this.
I use an AsyncTask for managing the downloads. I use this button so that each item in the list of cards can have the progress of the respective download. I am not sure how to report the status of the download to the RecyclerView. How do I get this to post updates to the cards?
The async downloader code is this
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
private final String resourceType;
public DownloadFileFromURL(String resourceType) {
super();
this.resourceType = resourceType;
// do stuff
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
String fileName = url.toString().substring(url.toString().lastIndexOf('/') + 1);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lengthOfFile = connection.getContentLength();
Log.d("lengthofFile", String.valueOf(lengthOfFile));
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
String destinationDirectory ="";
if(resourceType.equals(SyncUtil.IMAGE_ZIP)) {
destinationDirectory= SyncUtil.TMP;
}
if(resourceType.equals(SyncUtil.VIDEOFILE)) {
destinationDirectory = SyncUtil.VIDEO;
}
File mFolder = new File(AppController.root.toString() + File.separator+destinationDirectory);
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream output = new FileOutputStream(AppController.root.toString()+File.separator+destinationDirectory+File.separator
+ fileName);
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) / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
// closing streams
output.close();
input.close();
if(resourceType.equals(SyncUtil.IMAGE_ZIP)) {
BusProvider.getInstance().post(new ZipDownloadComplete(fileName,resourceType));
}
if(resourceType.equals(SyncUtil.VIDEOFILE)) {
// BusProvider.getInstance().post(new VideoDownloadComplete(fileName));
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
The RecyclerView adapter is here
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Video video = videosList.get(position);
holder.title.setText(video.getTitle());
holder.description.setText(video.getDescription());
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url ="http://"+ AppController.serverAddr +":"+AppController.port +"/video/"+video.getUrl()+video.getExtension();
DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(SyncUtil.VIDEOFILE);
downloadFileFromURL.execute(url,video.getTitle(),video.getDescription());
}
});
holder.bind(video,listener);
}
Though its not a very good solution but in my case I got that working. I'm just sharing my thoughts with some sample code snippet.
I assume you're showing the download progress with a ProgressBar. So take an instance of the ProgressBar in your adapter and pass the reference to your AsyncTask.
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Video video = videosList.get(position);
holder.title.setText(video.getTitle());
holder.description.setText(video.getDescription());
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url ="http://"+ AppController.serverAddr +":"+AppController.port +"/video/"+video.getUrl()+video.getExtension();
// Pass the progressBar here. You might have to set it as a final variable.
DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(SyncUtil.VIDEOFILE, holder.progressBar);
downloadFileFromURL.execute(url,video.getTitle(),video.getDescription());
}
});
holder.bind(video,listener);
}
Now modify your constructor of the AsyncTask like this.
public DownloadFileFromURL(... , ProgressBar mProgressbar) {
this.mProgressbar = mProgressbar;
this.mProgressbar.setProgress(0);
this.mProgressbar.setMax(100);
}
Add onProgressUpdate in your AsyncTask
protected void onProgressUpdate(Integer... values) {
mProgressbar.setProgress(values[0]);
}
Now in your doInBackground calculate the file size and publish the progress after a certain amount of file is downloaded.
protected void doInBackground() throws IOException {
try {
// Establish connection
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
final String contentLengthStr = connection.getHeaderField("content-length");
InputStream input = connection.getInputStream();
String data1 = f.getPath();
FileOutputStream stream = new FileOutputStream(data1);
byte data[] = new byte[4096];
int count;
int progressCount = 0;
while ((count = input.read(data)) != -1) {
stream.write(data, 0, count);
progressCount = progressCount + count;
int progress = (int) (((progressCount * 1.0f) / Integer.parseInt(contentLengthStr)) * 10000);
// Publish your progress here
publishProgress(progress);
}
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note:
Passing the original reference of your views is not a very good solution. I would rather set a BroadcastReceiver in my activity and would publish a broadcast with the specific item position in the publishProgress function. So that when the broadcast is received in the main activity, I could call notifyDatasetChanged to take progress effect in the list.
In my application, I have an expandablelistview and I want to open a PDF downloaded from the internet when I click on a specific child. The problem is that the pdf file (Read.pdf) is always empty, meaning that the download is not working.
Downloader Class:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Part of the Activity:
private void registerClick() {
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if ((groupPosition == 0) && (childPosition == 0)){
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file);
AbrirPDF.showPdf();
} else {
}
return false;
}
});
}
I think the OpenPDF (AbrirPDF) doesn't have any problem, but I will post it...
public class AbrirPDF {
public static void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf");
PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ContextGetter.getAppContext().startActivity(intent);
}
}
Thank you.
Ideally, your download should happen in a separate thread to avoid locking your app.
Here is an example that also includes a progress bar.
public class MainActivity extends Activity {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#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();
// 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(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
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
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
I wrote this code for downloading some files in my android application but now downloaded files are in the root without any special order and it looks very bad! So I want to know how can I add a folder for my application's downloaded files?
A code line to explain the path of output :
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + downloadedfileName);
And here is my code:
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
private String downloadedfileName;
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "بارگذاری...", Toast.LENGTH_SHORT).show();
pDialog = new ProgressDialog(DownloadActivity.this);
pDialog.setMessage("کتاب در حال بارگذاري، لطفا منتظر بمانيد...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(DownloadActivity.this)
.setTitle("دانلود کتاب با موفقیت انجام شد")
.setMessage("از دانلود شما سپاسگذاریم.")
.setNeutralButton("خواهش میکنم", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(DownloadActivity.this, LibActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
DownloadActivity.this.startActivity(i);
DownloadActivity.this.finish();
}
});
builder.create().show();
}
public void setDownloadedFileName(String downloadedfileName){
this.downloadedfileName = downloadedfileName;
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... surl) {
int count;
try {
URL url = new URL(surl[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
//OutputStream output = new FileOutputStream(Environment
// .getExternalStorageDirectory().toString()
// + "/data/" + downloadedfileName);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/ketabha/" + downloadedfileName);
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;
}
}
Just as simple change this to your favorite directory:
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/ANYFOLDER/ANOTHERFOLDER/" + downloadedfileName);
And remember that in the first create that directory with this code:
File dir = new File(yourdirectory);
if(!dir.exists()){
dir.mkdirs();
}
Above code work if you added related manifest in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and for more information see below links:
How to create directory automatically on SD card
Create folder in Android
can't create a folder in external storage on android device
I am doing a function to download files to android device, works fine but I want to do that if the downloaded file exists already in the device will overwrite it. Here is my code:
class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null){
this.finish();
}
else
{
Descargar.this.finish();
}
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
HttpURLConnection connection = null;
for (i=0; i< sUrl.length; i++) {
try {
URL url = new URL(sUrl[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
fOut = openFileOutput(i+".json",MODE_PRIVATE);
//fOut = new FileOutputStream("/aste/tiempobilbao.json");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
fOut.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (fOut != null)
fOut.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
return null;
}
}
If the file exist, delete it first.
you can delete file before starting download with below code :
File myFile = new File(fileName);
if(myFile.exists())
myFile.delete();
I need to program my apps to download the video first from server and save into sdcard before playing it. Where can i get this tutorial?
Current now, I stream the video, but i don't want this way.
final VideoView videoView = (VideoView)rootView.findViewById(R.id.styleVideo);
videoView.setVideoURI(Uri.parse(videoPath));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
videoView.setBackground(mScarfBuffer.getDrawable(position));
}
});
videoView.setMediaController(new MediaController(rootView.getContext()));
videoView.requestFocus();
videoView.start();
Use the following to download the file:
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
String SDCardRoot= Environment.getExternalStorageDirectory() ;
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"mydownloadmovie.mp4");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
}
}
Don't forget to wrap inside an AsyncTask.
Then use MediaPlayer to play your downloaded file( now local file).
this the code download and play the video on completed
public class Testing extends AppCompatActivity {
VideoView videoView;
MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing);
videoView = (VideoView) findViewById(R.id.vid258);
mediaController = new MediaController(this);
// Enter Your Server Link
final DownloadTask downloadTask = new DownloadTask(Testing.this);
downloadTask.execute("http://codechair.com/video/1496139752333.mp4");
});
}
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.mp4");
byte data[] = new byte[4096];
Log.d("Orignalvalu1",String.valueOf(new byte[4096]));
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
Log.d("Orignalvalu1",String.valueOf(input.read(data)));
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
Log.d("Orignalvalu2",String.valueOf(total));
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
videoView.setVideoPath("/storage/emulated/0/file_name.mp4");
videoView.setMediaController(mediaController);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
videoView.requestFocus();
videoView.start();
}
}