I am using glide to load GIF images into a RecyclerView.
Glide.with(context).load(imageUrl.trim())
.asGif()
.placeholder(R.drawable.coming)
.error(R.drawable.error)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(holder.gif_image);
if your GIF image on web
whatsapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
whatsappIntent.setType("image/*");
whatsappIntent.setPackage("com.whatsapp");
new Download_GIF(image).execute();
Uri imageUri = Uri.parse("file:///storage/emulated/0/downloadedFile.gif");
whatsappIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
try {
startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.whatsapp"));
startActivity(intent);
} catch (Exception e) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp"));
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
});
here whatsapp is imageButton
Download_GIF class
public class Download_GIF extends AsyncTask<String, Void, String> {
static String url_image=null;
public Download_GIF(String url) {
this.url_image = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String filepath = null;
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(url_image);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
String filename = "downloadedFile.gif"; // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
Log.i("Local filename:", "" + filename);
File file;
file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize);
}
//close the output stream when done
fileOutput.close();
if (downloadedSize == totalSize) filepath = file.getPath();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
}
Log.i("filepath:", " " + filepath);
return filepath;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
you can't share gifs between android apps because there's not a protocol for that.
sorry friend.
maybe if you want to share between apps built for you, you can serialize the image and a flag ( headers or another parameter ) to know it's a gif.
Related
I am using string array to hold images, i am fetching the imaes from the URLs. I have one imageview which when swipped changes the images in it. Now i want to download and save any image i want on the SD card and want it to appear in the phone gallery in a new folder.
I am using the following code but it is not working, it is showing no error at all.
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... arg0) {
downloadImagesToSdCard("", "");
return null;
}
private void downloadImagesToSdCard(String downloadUrl, String imageName) {
try {
URL url = new URL(thumb[j]);
/* making a directory in sdcard */
String sdCard = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(sdCard, "test.jpg");
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File(myDir, fname);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadedSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
} catch (IOException io) {
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And i am executing it by
new ImageDownloadAndSave().execute("");
the name of my string array is "thumb" which is holding all the URLs. What am i doing wrong?
You should add image to gallery after save and then scan it. Please check the following topics:
Image, saved to sdcard, doesn't appear in Android's Gallery app
MediaScannerConnection
The file needs to be added to the Android MediaStore. This can be done easily by using below function.
public void scanFile(final File file) {
try {
new MediaScannerConnectionClient() {
private MediaScannerConnection mMs;
public void init() {
mMs = new MediaScannerConnection(myContext, this);
mMs.connect();
}
#Override
public void onMediaScannerConnected() {
mMs.scanFile(file.getAbsolutePath(), null);
mMs.disconnect();
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
}.init();
} catch(Exception e) {
// Device does not support adding files manually.
// Sending Broadcast to start MediaScanner (slower than adding manually)
try {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
} catch(Exception ee) {
// Something went terribly wrong.
// Can't add file to MediaStore and can't send Broadcast to start MediaScanner.
}
}
}
You just need to add one line to your code:
// .....
fos.close();
Log.d("test", "Image Saved in sdcard..");
scanFile(file); // <------------- add this
How to attach image in email? I am able to attach text in email but not attach image properly,
so only send the Text but not send the Image.
Problem with,
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
so Control direct put in catch statement after urlConnection.connect();, Image not save in SDACRD.so not attach the image. How to do?
My code in Below,
urlShare = "http://example.com/share.php?id="+ strId;
public class sendImageThroughEmail extends AsyncTask<Void, Void, Void> {
/** Hashmap for Share */
ArrayList<HashMap<String, String>> arrDataList = null;
String strMessage = null, strImageLocator = null;
ProgressDialog progressDialog;
String filePath, strImageName;
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
arrDataList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONFunctions.getJSONfromURL(urlShare);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
strMessage = jsonobject.getString(TAG_MESSAGE);
strImageLocator = jsonobject.getString(TAG_DATA);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
URL url = new URL(strImageLocator);
//URL url = new URL("http://example.com/upload/images (8).jpg");
strImageName = strImageLocator.substring(strImageLocator
.lastIndexOf('/') + 1);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = strImageName;
Log.i("Local File:", filename);
File file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fileOutput.close();
if (downloadedSize == totalSize) {
filePath = file.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
Intent email = new Intent(Intent.ACTION_SEND);
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = strImageName;
File file = new File(SDCardRoot, filename);
Uri markPath = Uri.fromFile(file);
email.putExtra(Intent.EXTRA_STREAM, markPath);
email.putExtra(Intent.EXTRA_SUBJECT, "Share");
email.putExtra(Intent.EXTRA_TEXT, strMessage);
email.setType("image/png");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email Client"));
}
};
My ImageLocator Like this,
1) http://example.com/upload/images (8).jpg
2) http://example.com/upload/11_2134_232222_33.png
Please Guide me.
Thanks in advance...
Edit following strings in your email intent:
//...
email.setType("image/jpeg");
email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath()));
//...
For more info you can see this answer.
EDIT
To download file use this code:
private final static String SD_CARD = Environment
.getExternalStorageDirectory().getAbsolutePath();
private final static String PNG = ".png";
private final static String APP_FOLDER = "Folder Name";
/**
* Checking if the SD card is mounted
*
* #return SD card existence
*/
public static boolean isSdPresent()
{
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* Downloads image file onto SD card in specific folder
*
* #param fileUrl URL for downloading of file
* #throws IOException
*/
private static void downloadImage(String fileUrl) throws IOException
{
if (isSdPresent())
{
if (fileUrl.length() > 0)
{
URL url = new URL(fileUrl);
InputStream input = url.openStream();
File folder = new File(SD_CARD, APP_FOLDER);
if (!folder.exists())
folder.mkdir();
OutputStream output = new FileOutputStream(new File(folder,
fileUrl.substring(fileUrl.indexOf("=") + 1, fileUrl.length())
+ PNG));
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
output.close();
input.close();
}
}
else
{
if (BuildConfig.DEBUG)
Log.e("SD card", "not mounted");
}
}
i have An Error while download PDF file From Server and save it on SD
i have permission To Access internet and external storage ..
It`s working fine on android 2.3.6
But on Tab 4.1.1 its create the file with 0 byte
URL url = new URL("https://docs.google.com/"+direct);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "application/xml");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/folder/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,book.getBook_name()+".pdf");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
publishProgress((downloadedSize*100)/totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this:
private String getExternalSDPath() {
File file = new File("/system/etc/vold.fstab");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
// handle
}
String path = null;
try {
if (fr != null) {
br = new BufferedReader(fr);
String s = br.readLine();
while (s != null) {
if (s.startsWith("dev_mount")) {
String[] tokens = s.split("\\s");
path = tokens[2]; // mount_point
if (Environment.getExternalStorageDirectory()
.getAbsolutePath().equals(path)) {
break;
}
}
s = br.readLine();
}
}
} catch (IOException e) {
// handle
} finally {
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
// handle
}
}
return path;
}
The code is made specifically for Samsung Devices with both internal, an internal that acts as external, and SD.
I needed to access the SD and came up with the above code, so you can try it and possibly modify it to work on all devices.
Edit: My download AsyncTask
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "somefile.pdf";
HttpURLConnection c;
try {
URL url = new URL("http://someurl.com/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file= new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
} else {
return "Unable to create folder";
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}
I want that If my app start first time it should download image from web and store that image in Device/Emulator, from Device/Emulator that should be displayed in ImageView.
I have tried in this way :
ImageView myImgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImgView = (ImageView) findViewById(R.id.imageView1);
new MyAsnyc();
Log.d(MY_TAGT, "AsyncTask Executed.....");
}
private class MyAsnyc extends AsyncTask<Void, Void,Void>{
public File file ;
InputStream is;
private Bitmap bitmap;
protected void doInBackground() throws IOException{
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL(BASE_URL);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
Log.i(MY_TAGT, "Picture is readable........");
os.write(data);
Log.i(MY_TAGT, "Picture is Saved........");
is.close();
os.close();
}
catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(){
try{
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
catch (Exception e) {
// TODO: handle exception
}
/*Here I want to set this image in ImageView*/
bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");
myImgView.setImageBitmap(bitmap);
}
}
But in this way MyAsync class is not executed, please tell how to do that.
EDIT this is my log
Use execute to call it.
new MyAsnyc().execute();
use
new MyAsnyc().execute();
instead of
new MyAsnyc();
because AsyncTask.execute(Params... params) method used for executing an AsyncTask
EDIT :
use While or for loop for writing data in file as :
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
Log.i(MY_TAGT, "Picture is readable........");
int count;
while ( (count = is.read(data)) >= 0 ) {
os.write(data,0,count)
}
Log.i(MY_TAGT, "Picture is Saved........");
is.close();
os.close();
You must try this :
public class DownloadImage {
public static File getImage(String imageUrl, String fileName){
File file = null;
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(imageUrl);
Log.d("INFORMATION..", "FILE FOUNDED....");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
Log.d("INFORMATION..", "FILE CONECTED....");
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
file = new File(SDCardRoot, fileName);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
Log.d("INFORMATION..", "WRINTING TO FILE DOWNLOADED...." + file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
Log.d("INFORMATION..", "FILE DOWNLOADED....");
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
Log.d("INFORMATION..", "FILE DOWNLOADING COMPLETED....");
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
Call this DownloadImage.getImage(String imageUrl, String fileName) in MainActivity.java like this :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
String url = "http://4.bp.blogspot.com/-8v_k_fOcfP8/UQIL4ufghBI/AAAAAAAAEDo/9ffRRTM9AnA/s1600/android-robog-alone.png";
String file = DownloadImage.getImage(url, "My Image.jpg").toString();
// Get file path on device and set it to imageView
Bitmap bitmap = BitmapFactory.decodeFile(file);
imageView.setImageBitmap(bitmap);
}
}
I think this what you are looking for! hope this will help you
You forgot to execute the AsyncTask:
(new MyAsnyc()).execute();
Before line Log.d(MY_TAGT, "AsyncTask Executed.....");
you just construct new AsyncTask object but you didn't call execution on it with execute() method..
EDIT: second problem is that it is not so clear WHICH picture actually you want to display in that ImageView.. cause bitmap = BitmapFactory.decodeFile(..blahblahblah..) will probably be null after this.. It seems to me u r giving folder name and you wanted to decode that "file" to bitmap.. Make some logs about this decoding and bitmap value and show us..
Edit2:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
bitmap = BitmapFactory.decodeFile(file);
should work a bit better..
It works just fine when I run it in a thread, but I want to use Asynctask and when I execute my version of it, nothing happens:
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(filename2);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,filename3);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
//int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
THIS IS MY ATTEMPT AS REQUESTED:
private class DownloadFile extends AsyncTask<Void, Integer, Long> {
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
Intent in = new Intent(mainmenu.this, DownloadService.class);
stopService(in);
}
#Override
protected Long doInBackground(Void... params) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(filename2);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,filename3);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
//int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
here you go
public class WebRequest extends AsyncTask<URL, Void, String> {
ProgressDialog dialog;
Context _context;
String _title;
String _message;
public WebRequest(Context context,
String ProgressTitle, String ProgressMessage) {
this._context = context;
this._title = ProgressTitle;
this._message = ProgressMessage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new ProgressDialog(_context);
dialog.setTitle(_title);
dialog.setMessage(_message);
dialog.show();
}
#Override
protected String doInBackground(URL... params) {
// TODO Auto-generated method stub
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = params[0];
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,filename3);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
//int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
return "Success";
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
return "Failed";
} catch (IOException e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (dialog.isShowing())
dialog.cancel();
Toast.makeText(_context,result,Toast.LENGTH_LONG);
}
}
//using this
WebRequest request = new WebRequest(context,"Downloading","Please wait..");
request.Execute(object of URL);