I'm developing an Android application for downloading a file from
server and save that file to the path specified..
I want to make this happen in the background, So I code the downloading function in service. Now I'm getting an error when I used the code in my service..
Can anyone help me to find the error... Thank You..
My Service code Is...
public class MyService extends Service {
Contacts c = new Contacts();
// File url to download
private static String file_url = "http://f23.wapka-files.com/download/6/9/4/1408248_69459e029be95f96ff9f98ff.mp3/a0f9f2173d3d81a49c28/01-Podimeesha-Anand.Madhusoodhanan.mp3y";
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!folder.exists()) {
try {
folder.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + folder);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.srt");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
MyService.this.stopService(intent);
return super.onStartCommand(intent, flags, startId);
}
/**
* 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 {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
// 6yi7 conection.connect();
conection.setRequestProperty("Accept-Encoding", "identity");
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(c.getA());
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;
}
#Override
protected void onPostExecute(String file_url) {
Toast.makeText(MyService.this, "Downloaded Succesfully.. check Jithin's folder 2 see file...", Toast.LENGTH_LONG).show();
//my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
My Main Activity code is..
public void download(View view) {
String value = getIntent().getExtras().getString("id");
if (value.equals("Song0")) {
Intent i=new Intent(Song_List.this, MyService.class);
startActivity(i);
Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
}
}
Change your code from,
Intent i=new Intent(Song_List.this, MyService.class);
startActivity(i);
this to,
Intent i=new Intent(Song_List.this, MyService.class);
startService(i);
First of all you should start your service like this not with startActivity
public void download(View view) {
String value = getIntent().getExtras().getString("id");
if (value.equals("Song0")) {
Intent i=new Intent(Song_List.this, MyService.class);
startService(i);
Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
}
}
after stop service when your file download is completed
MyService is the extention of Service. So you have to use startService(Intent).
so your code may look like this :
public void download(View view) {
String value = getIntent().getExtras().getString("id");
if (value.equals("Song0")) {
Intent i=new Intent(Song_List.this, MyService.class);
startService(i);
Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
}
}
Related
I had created downloading task using intent service. which shows notification with progress bar with percentage.I'm using local broadcast manager to pass data while downloading.I also add one button to cancel download in notification but the problem is while i'm clicking on cancel Download it not stop Intent service. how can i stop intent service. Here i put my code of Intent service and also broadcast receiver to close service.
public class DownloadService extends IntentService {
public DownloadService() {
super(DownloadService.class.getName());
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
InputStream input;
OutputStream output;
HttpURLConnection connection;
Intent intent1 = new Intent();
intent1.setAction("com.demo.downloading");
try {
URL url = new URL(urlToDownload);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
}
final int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[8192];
long total = 0;
int count, latestPercentDone;
int percentDone = -1;
while ((count = input.read(data)) != -1) {
total += count;
latestPercentDone = (int) (total * 100 / fileLength);
if (percentDone != latestPercentDone) {
percentDone = latestPercentDone;
if (percentDone < 100) {
if (percentDone != 0) {
intent1.putExtra("progress", "" + percentDone);
intent1.putExtra("IsCancel", false);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
}
}
if (percentDone == 100) {
intent1.putExtra("progress", "" + 0);
intent1.putExtra("IsCancel", false);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
}
}
output.write(data, 0, count);
if (StaticFields.cancelDownload) {
Log.d(TAG, "onHandleIntent: Download Cancel");
this.stopSelf();
}
}
output.close();
} catch (IOException e) {
intent1.putExtra("progress", "" + (-1));
intent1.putExtra("IsCancel", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
e.printStackTrace();
is_all_download = false;
}
}
}
My broadcast receiver class
OnReceive method ()
if (intent.getAction() != null) {
if (action.equals("notification_cancelled")) {
Global.cancelDownload = true;
Intent intent1 = new Intent();
intent1.setAction("com.demo.downloading");
intent1.putExtra("IsCancel", true);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
}
}
}
LocalBroadcast manager receive method
boolean isCancel = intent.getBooleanExtra("IsCancel", false);
if (isCancel) {
Global.cancelDownload = true;
mContext.stopService(serviceIntent);
}
In an IntentService, onHandleIntent() is called on a worker (background) thread. When you call stopService(), this has no effect on the worker threads, as they will still run to completion. Calling stopService() on an IntentService makes no sense anyway, since an IntentService runs when it has work to do and stops itself when all of the work is finished.
Instead of calling stopService(), you need to set a flag in your Service that can be checked in the loop in your onHandleIntent() method. If the flag is set, you should abort further processing in your loop and end the worker thread yourself.
I'm Developing an android application to download .mp3 from Server.
When clicked on the download button ProgressBar will appear,displaying the
percentage on screen.
This works fine. Now i want to make that download work in background by Showing Notification with a ProgressBar
can anyone help me to find a code to Use the Service and Building Notification?Thank You
My MainActivity.java code:
public class MainActivity extends Activity {
final MediaPlayer mp=new MediaPlayer();
//---------------------
Clone c=new Clone();
//------------------
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://www.eecindia.co.in/up/01%20-%20Pretham%20-%20Oruthikku%20Pinnil%20[Maango.me].mp3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//----------------------------------------------
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select The Extension To Download...");
builder.setItems(new CharSequence[]
{".mp3", ".mp4", ".txt", ".srt"},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
/////////////////////////////////////////////////////////////////
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!folder.exists()) {
try {
folder.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + folder);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.mp3");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
/////////////////////////////////////////////////////////////
break;
case 1:
////////////////////////////////////////////////////////////
File folde = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!folde.exists()) {
try {
folde.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + folde);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.mp4");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
////////////////////////////////////////////////
break;
case 2:
File fold = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!fold.exists()) {
try {
fold.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + fold);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.txt");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
break;
case 3:
File fol = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!fol.exists()) {
try {
fol.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + fol);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.srt");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
break;
}
}
});
builder.create().show();
/////-------------------------------------
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading File. Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* 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();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
// 6yi7 conection.connect();
conection.setRequestProperty("Accept-Encoding", "identity");
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(c.getA());
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
try {
pDialog.setProgress(Integer.parseInt(progress[0]));
} catch (Exception d) {
Log.d("Error .. ", d.getMessage());
}
}
/**
* After completing background task
* Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
Toast.makeText(MainActivity.this, "Downloaded Succesfully.. check Jithin's folder 2 see file...", Toast.LENGTH_LONG).show();
//my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
//---------------------------------
protected void onStop(){
super.onStop();
Intent intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
}
You can use foreground Notification.Here is your Example
project demonstrating the use of startForeground().
I have good concept of starting and using the basic service. I mean not to complicated. In My app I want a service which should not be killed in any situation and should download some files from the server then it should call stopSelf. I have made my service in the following way. But before sharing its whole code just let me tell you what I am doing
In Service I am passing the series of url (string array) which has to download all files from the server.
I am using the async task to download from the server.
Under this whole process I am getting a 1st response that is in xml then I parse it , and get the JSON string (sorry about that my web service designer is a numb like me). so after these two conversion I store the data in the database and then starts downloading files and saving them to device and store their path in the database. (this all works fine)
I am calculating and updating progress in the notification bar. (showing user how much the files has been downloaded)
what I really want
I want that my service should not be killed when user removes it from the recent app list , so that it should continue to download and continue to update the status in notification bar. I am using Notification manager to update the progress.
What is really happening
When I close my app from recent app tray, I think my service gets killed and the downloading process stops, and It also stops updating the progress of notification in notification bar, Where As I want it to continue to run until the download process is finished.
Here is my code it is simplified as some methods are really not worthy
to be discussed here Such as Parsing the xml or JSON
Here is the Code
public class MyDemoService extends Service {
private static final String TAG = "MyDemoService";
private static final int NOTIFICATION_ID = 1;
private LocalBinder m_binder = new LocalBinder();
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
myAsyncTask myWebFetch;
// Timer to update the ongoing notification
private final long mFrequency = 100; // milliseconds
private final int TICK_WHAT = 2;
public class LocalBinder extends Binder {
MyDemoService getService() {
return MyDemoService.this;
}
}
private Handler mHandler = new Handler() {
public void handleMessage(Message m) {
updateNotification();
sendMessageDelayed(Message.obtain(this, TICK_WHAT), mFrequency);
}
};
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "bound");
return m_binder;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "created");
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d(TAG, "Removed");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroyed");
}
public void updateNotification() {
// Log.d(TAG, "updating notification");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
}
public void hideNotification() {
Log.d(TAG, "removing notification");
mNotifyManager.cancel(NOTIFICATION_ID);
mHandler.removeMessages(TICK_WHAT);
}
public void start() {
Log.d(TAG, "start");
mBuilder =
new NotificationCompat.Builder(MyDemoService.this)
.setSmallIcon(R.drawable.download)
.setContentTitle("SMU")
.setContentText("Downloading Images");
Intent targetIntent = new Intent(MyDemoService.this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MyDemoService.this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
myWebFetch = new myAsyncTask();
myWebFetch.execute();
}
class myAsyncTask extends AsyncTask<String, Integer, Void> {
MyDB myDB;
myAsyncTask() {
myDB = new MyDB(MyDemoService.this);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
// Removes the progress bar
mBuilder.setProgress(0, 0, false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
#Override
protected Void doInBackground(String... params) {
//set the download URL, a url that points to a file on the internet
getJSON("http://*****", 1000000);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
public void getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setInstanceFollowRedirects(false);
c.connect();
int status = c.getResponseCode();
if (status == 200) {
String readStream = readStream(c.getInputStream());
if (readStream != null) {
JsonParser mJsonParser = new JsonParser(MyDemoService.this);
mJsonParser.parseJaSon(readStream);
ArrayList<SuitDetails> mImageList = new ArrayList<>(myDB.GetAllData());
if (mImageList != null) {
//NOW HERE DOWNLOADING IMAGES FROM URL WE GOT SAVED IN DB AFTER PARSING
downloadImages(mImageList);
}
}
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private String readStream(InputStream in) {
//parsing my input stream and sending back string
return jsonString.toString();
}
void downloadImages(ArrayList<SuitDetails> arrayList) {
try {
ArrayList<SuitDetails> imageUrl = arrayList;
URL url;
float progressImages = 0;
HttpURLConnection urlConnection = null;
for (int i = 0; i < imageUrl.size(); i++) {
progressImages += 100 / imageUrl.size();
publishProgress((int) progressImages);
url = new URL(imageUrl.get(i).getPath().toString());
//create the new connection
urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setConnectTimeout(60000);
urlConnection.setReadTimeout(60000);
urlConnection.setInstanceFollowRedirects(false);
//and connect!
urlConnection.connect();
File storagePath = new File(MyDemoService.this.getExternalFilesDir("TEST") + "/Mytest");
storagePath.mkdirs();
String finalName = imageUrl.get(i).getImageName();
File myImage = new File(storagePath, finalName + ".png");
FileOutputStream fileOutput = new FileOutputStream(myImage);
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) {
//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
}
//close the output stream when done
ContentValues contentValues = new ContentValues();
contentValues.put("Status", "1");
contentValues.put("Path", myImage.getPath().toString());
myDB.UpdateDownloadStatus(contentValues, imageUrl.get(i).getSImageID());
fileOutput.close();
}
myDB.closeDb();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I Know this is length code but sharing if You want to analyse it deeply.
I will provide how I am using and calling this service in MainActivity if you demand it
why are you not using an IntentService if you want to do network stuff?
you should consider adding setIntentRedelivery(true); in your constructor
from the documentation
Sets intent redelivery preferences. Usually called from the
constructor with your preferred semantics.
If enabled is true, onStartCommand(Intent, int, int) will return
START_REDELIVER_INTENT, so if this process dies before
onHandleIntent(Intent) returns, the process will be restarted and the
intent redelivered. If multiple Intents have been sent, only the most
recent one is guaranteed to be redelivered.
If enabled is false (the default), onStartCommand(Intent, int, int)
will return START_NOT_STICKY, and if the process dies, the Intent dies
along with it.
I'm tryinig to create a service to download a file from a server, in my local network.Every think seems to be ok ,the service starts, when the download ends ,when i check for the file in the sdcard i found an emty file ,can someone help me to solve this problem ,Thank you in advance.
This the service DownloadService :
public class DownloadService extends Service{
private static String file_url = "http://192.168.1.150:8080/TestAndroid/DownloadServlet/Desert.pdf";
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show();
new DownloadFileFromURL().execute(file_url);//Appel vers Asynctask
return START_STICKY;
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
public String[] listDebitDown = new String[163] ;
int compteur = 0;
#Override
protected void onPreExecute() {
super.onPreExecute();
// showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#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("/sdcard/downloadedfile.pdf");//jpg
int nombrePaquets ;
nombrePaquets = (lenghtOfFile / 1024 ) + (lenghtOfFile % 1024 );
byte data[] = new byte[1024];
String tabResult [] = new String [nombrePaquets];
long total = 0;
long startTotalTime = System.currentTimeMillis();
long passedTime =0;
// Get ListView object from xml
// listView = (ListView) findViewById(R.id.listView1);
while ((count = input.read(data)) != -1) {
total += count;
// 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;
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
Toast.makeText(getApplicationContext(),
"téléchargement términé " , Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
"Passagr "+ listDebitDown[10] , Toast.LENGTH_LONG)
.show();
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";//jpg
Log.i("imagePath", imagePath);
Log.i("isExternalStorageWritable", isExternalStorageWritable() + "true" );
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.i("isExternalStorageWritable", "true" );
return true;
}
return false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
PS:of corse i added permission ,the server can ping to the phone ,the wamp server is ON .
Try to store file in external storage.
File mFile= new File(Environment.getExternalStorageDirectory(), "downloadedfile.pdf");
if(!mFile.isExist()){
mFile.createNewFile();
}
then
OutputStream output = new FileOutputStream(mFile,true);
I am developing an application, which focus mainly on downloading a file from web service and storing it in sd card. Everything went easy until my client needs to cancel the on going download. I tried many ways but i failed. So can any one help me out and post some snippets for cancelling on going download. Intent service will be much preferred.
Edit:
Toast.makeText(ThumbnailView.this, R.string.Download_start, Toast.LENGTH_SHORT).show();
pb.setVisibility(View.VISIBLE);
info_icon.setVisibility(View.INVISIBLE);
langBtn.setVisibility(View.INVISIBLE);
name.setVisibility(View.INVISIBLE );
author.setVisibility(View.INVISIBLE );
lastReading.setVisibility(View.INVISIBLE);
intent = new Intent(ThumbnailView.this,
DownloadAndExtractFiles.class);
Common.isDownloadProgress = true;
intent.putExtra("BEAN", bean);
intent.putExtra("FROM", "library");
intent.putExtra("receiverTag", mReceiver);
startService(intent);
IntentService Class:
try {
File file = new File(path, /* BOOK_ID */filename + fileformat);
if (file.exists())
file.delete();
file.createNewFile();
output = new FileOutputStream(file);
finalpath = path + "/" + filename + fileformat;
Log.d("book UNEXTR path", finalpath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (Common.downloadChkLogout) {
// Changed on saturday 9th nov
//if (Common.isDownloadProgress) {
if (stopped) {
break;
}
total += count;
Bundle resultData = new Bundle();
resultData.putInt("progress",
(int) (total * 100 / lenghtOfFile));
bean.setProgress((int) (total * 100 / lenghtOfFile));
rec.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
}
success = true;
//}
output.flush();
output.close();
input.close();
} catch (Exception ex) {
ex.printStackTrace();
mError = "Download Failed";
System.out.println("Net Disconnect;:" + mError);
Toast.makeText(getApplicationContext(), mError,
Toast.LENGTH_LONG).show();
}
Edit:
public void onClick(DialogInterface dialog,int id) {
Log.i("Aftr before service stopped---->>>>>", "true");
Log.i("Intent obj","Intent check..."+intent);
if(intent!=null)
{
Common.isDownloadProgress = false;
stopService(intent);
This is my cancel click
I have posted my code for starting the service, and downloading part on onHandleIntent
Thanks in advance :)
you need to check whether it's stopped or not from within your service and you are half done on that line
if (stopped)
break;
now make stopped a static boolean and set it to true on button click,
Edit
You are already checks Common.isDowloadProgress but it's commented and I believe you need to break the loop as follows
while ((count = input.read(data)) != -1)
{
if (Common.downloadChkLogout)
{
if (Common.isDownloadProgress)
{
if (stopped)
{ break; }
total += count;
Bundle resultData = new Bundle();
resultData.putInt("progress",
(int) (total * 100 / lenghtOfFile));
bean.setProgress((int) (total * 100 / lenghtOfFile));
rec.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
else
{ break; }
}
}
success = true;
I thing you should use AsyncTask for downloading items, It porvide on cancel event as well.
Let say you are using HttpGet to download you file, your task will look like...
public class FileDownloadingTask extends AsyncTask<Void, Void, Void> {
private String url = null;
private String destPath = null;
private HttpGet httpGet = null;
// Constructor
public FileDownloadingTask(String url, String destPath) {
this.url = url;
this.destPath = destPath;
}
// Create a progress dialog in your onPreExecute
// Start downloading in your doInBackground and save to destPath in sd-card
// Proform any thing your want in response to download process in onPostCreate
// Finally...
#Override
protected void onCancelled() {
super.onCancelled();
// Aborting http request
if (httpget != null) {
httpget.abort();
}
}
// Then in your cancel button of progress dialog call this.onCancel();
}
Hope this will give you some hint...:)
Add this on your button click. Modify the if condition to suit your needs. I am uploading a video and when i click on remove, this happens :-
if(processFileUploadTask !=null && processFileUploadTask.getStatus() != AsyncTask.Status.FINISHED){
Thread t = new Thread(new Runnable() {
public void run() {
if(httpost != null ){
httpost.abort();
}
}
});
t.start();