PDA

View Full Version : کلاس دانلود فایل با دانلود منیجر



samiasoft
دوشنبه 01 مرداد 1397, 22:54 عصر
سلام دوستان

برای دانلود فایل با دانلود منیجر چنین کلاسی رو بصورت زیر ایجاد کردم اما

مشکلی که داشتم این هستش که :

1- چگونه وقتی دانلود تمام شد نوتیفیکیشن دانلود رو پاک کنیم ؟

2- چگونه دانلود را کنسل کنیم هنگام خارج شدن از برنامه؟

public class Download_Manager {

private Context context;
DownloadManager manager;
DownloadManager.Request request;




public Download_Manager(Context context) {
this.context = context;
}


public void startDownload(String url) {




request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");


request.setTitle("Some title");


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager. Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}


String filename=url.substring( url.lastIndexOf('/')+1, url.length() );


request.setDestinationInExternalPublicDir(Environm ent.DIRECTORY_DOWNLOADS, filename);




manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE) ;
context.registerReceiver(onComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPL ETE));
manager.enqueue(request);


Toast.makeText(context, "آغاز دانلود در نوتیفیکیشن", Toast.LENGTH_SHORT).show();




}




BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(context, "دانلود کامل شد", Toast.LENGTH_SHORT).show();
}
};












}

farhad_shiri_ex
سه شنبه 02 مرداد 1397, 05:40 صبح
با سلام!
اول اینکه این کللاس که ناقص گذاشتی اینجا اگر امکانش هست کامل بذار ؟!

ولی از اونجا که مشخصه داره یک BroadCast را رجیستر میکنه ودر زمان استارت سرویس توی یک نخ دیگه دانلود را انجام میده!
خوب کافی به سرویسی که استارت شده فرمان Stop بدی و نخی هم که داره دانلود میشه کنسل کنی!
حالا اگر کلاس سرویس و نخ خودت نوشتی که خوب خیلی راحت به آبجکتهای کلاس دسترسی داری چون نمی دونم مکانیزم نخی که داری چطوری خیلی نمی تونم کمک کنم.
ولی اگر نه از کلاس های مثل AsyncTask و برای سرویس هم کلاس آماده هست که در اینصورت هم که خیلی ساده ست متوقف کردن سرویس.
برای نوتیفیکیشن هم اگر خودت داری ارسال میکنی که با کد زیر میتونی بهش دسترسی داشته باشی!

NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(Context.N OTIFICATION_SERVICE);
Objects.requireNonNull(nMgr).cancel(0);


در کل استفاده از کلاس JobService خیلی بهتر از کلاس Service هست.

samiasoft
شنبه 06 مرداد 1397, 14:45 عصر
تشکر از شما...از این کلاس استفاده کردم و به راحتی فایل رو دانلود میکنه و با پروگریس بار هم نمایش میده

public 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();


//نام فایل ذخیره..که همان نام اصلی فایل در نظرگرفتیم
String filename=url.toString().substring( url.toString().lastIndexOf('/')+1, url.toString().length() );


// download the file
input = connection.getInputStream();
output = new FileOutputStream(context.getFilesDir()+"/" +filename);


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));
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();
((MainActivity) context).mProgressDialog.show();
}


@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);


//نمایش میزان پیشرفت دانلود
((MainActivity) context).mProgressDialog.setIndeterminate(false);
((MainActivity) context).mProgressDialog.setMax(100);
((MainActivity) context).mProgressDialog.setProgress(progress[0]);
}


@Override
protected void onPostExecute(String result) {


//کدهای این قسمت زمانی اجرا میشود که فایل بطور کامل دانلود شده باشد
// dismissDialog(progress_bar_type);
mWakeLock.release();
((MainActivity) context).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();
((MainActivity) context).load_image();
}
}