У меня есть функция с именем DownloadTask.java, я вызываю ее в другой деятельности, new Download Task (.this, URL);
При загрузке после этого всплывающего текста «Успешная загрузка» отображается диалоговое окно, но я хочу показать индикатор выполнения в уведомлении, чтобы пользователь мог легко найти загружаемый файл.
Ниже приведен код для DownloadTask.java
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());//Create file name by picking download file name from URL
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
int progress = 0;
NotificationCompat.Builder notificationBuilder;
NotificationManager notificationManager;
int id = 10;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading...");
progressDialog.show();
}
@Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
Toast.makeText(context, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if exception occurs
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "App Name");
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
}
И код для другого действия, где происходит загрузка:
public class SessionActivity extends AppCompatActivity {
private Button btnDownload;
private String userName,passWord,getUrl,htmlData,divElement;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
String URL = "https://s3.amazonaws.com/sample.pdf";
private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
;
}
private void requestPermissionAndContinue() {
if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
&& ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = null;
try {
alertBuilder = new AlertDialog.Builder(this);
} catch (Exception e) {
e.printStackTrace();
}
alertBuilder.setCancelable(true);
alertBuilder.setTitle(getString(R.string.downloadCompleted));
alertBuilder.setMessage(R.string.downloadCompleted);
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(SessionActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
, READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
Log.e("", "permission denied, show dialog");
} else {
ActivityCompat.requestPermissions(SessionActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
} else {
openActivity();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (permissions.length > 0 && grantResults.length > 0) {
boolean flag = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
flag = false;
}
}
if (flag) {
openActivity();
} else {
finish();
}
} else {
finish();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void openActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_session);
if (!checkPermission()) {
openActivity();
} else {
if (checkPermission()) {
requestPermissionAndContinue();
} else {
openActivity();
}
}
final Intent Intent = getIntent();
userName = Intent.getStringExtra("number");
passWord = Intent.getStringExtra("birthDate");
String txt4 = ".pdf";
String url3 = URL + userName + txt4;
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String txt4 = ".pdf";
new DownloadTask(SessionActivity.this, URL);
}
});
Button imageLogo = (Button) findViewById(R.id.btnviewslip);
imageLogo.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "file_url_to_download/";
String txt3 = ".pdf";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(URL + userName + txt3));
startActivity(i);
}
});
}
}