👉 AndroidManifest.xml :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
👉 DownloadSingleTask :
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.evoli.sanghvi.sanghvi.R;
import com.evoli.sanghvi.sanghvi.common.ServerSettings;
import com.evoli.sanghvi.sanghvi.interfaces.AsyncResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class DownloadSingleTask {
private static final String TAG = "Download Task";
public AsyncResponse delegate = null;
private Context context;
private String downloadUrl;
public DownloadSingleTask(AsyncResponse asyncResponse, Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = ServerSettings.Main_URL + downloadUrl;
delegate = asyncResponse;
//Start Downloading Task
new DownloadSingleTask.DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<String, Integer, Void> {
private int PROGRESS_MAX = 100;
private int PROGRESS_CURRENT = 0;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
private int notificationID_;
private File apkStorage = null;
private File outputFile = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
notificationID_ = Application_shangvi.NotificationID.getID();
mBuilder = new NotificationCompat.Builder(context, "notify_001");
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadInProgress));
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setColor(context.getResources().getColor(R.color.colorLogo));
mBuilder.setOnlyAlertOnce(true);
mBuilder.setProgress(0, 0, true);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001", "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
}
@Override
protected void onPostExecute(Void result) {
try {
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
if (outputFile != null) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadCompleted));
mBuilder.setProgress(0, 0, false);
mNotificationManager.notify(notificationID_, mBuilder.build());
}
}, 2000);
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadAgain));
mBuilder.setProgress(0, 0, false);
mNotificationManager.notify(notificationID_, mBuilder.build());
}
}, 2000);
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() {
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadAgain));
mBuilder.setProgress(0, 0, false);
mNotificationManager.notify(notificationID_, mBuilder.build());
}
}, 2000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
try {
delegate.processFinish(true);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
protected void onProgressUpdate(Integer... progress) {
mBuilder.setProgress(PROGRESS_MAX, progress[0], true);
// Displays the progress bar on notification
mNotificationManager.notify(notificationID_, mBuilder.build());
}
@Override
protected Void doInBackground(String... params) {
try {
Calendar calendar = Calendar.getInstance();
String date = fromInt(calendar.get(Calendar.MONTH))
+ fromInt(calendar.get(Calendar.DAY_OF_MONTH))
+ fromInt(calendar.get(Calendar.YEAR))
+ fromInt(calendar.get(Calendar.HOUR_OF_DAY))
+ fromInt(calendar.get(Calendar.MINUTE))
+ fromInt(calendar.get(Calendar.SECOND));
String[] subFileName = downloadUrl.split("/");
String downloadFileName = date.toString() + subFileName[subFileName.length - 1];
Log.e(TAG, downloadUrl);
Log.e(TAG, downloadFileName);
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//Open Url Connection
httpURLConnection.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
httpURLConnection.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + httpURLConnection.getResponseCode()
+ " " + httpURLConnection.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(Environment.getExternalStorageDirectory(), "/" + context.getResources().getString(R.string.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 = httpURLConnection.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
publishProgress(Math.min(PROGRESS_CURRENT * 10, 100));
PROGRESS_CURRENT++;
}
//Close all connection after doing task
fos.close();
is.close();
scanPhoto(context, outputFile.toString());
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
public static String fromInt(int val) {
return String.valueOf(val);
}
public static void scanPhoto(Context context, String imageFileName) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imageFileName);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
}
👉 Call this class :
ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
new DownloadSingleTask(new AsyncResponse() {
@Override
public void processFinish(Object output) throws UnsupportedEncodingException {
}
}, this, url);
} else {
Toast.makeText(Activity_Main.this, getResources().getString(R.string.NoInternet), Toast.LENGTH_LONG).show();
}
👉 strings.xml :
<string name="NoInternet">No Internet connection</string>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
👉 DownloadSingleTask :
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.evoli.sanghvi.sanghvi.R;
import com.evoli.sanghvi.sanghvi.common.ServerSettings;
import com.evoli.sanghvi.sanghvi.interfaces.AsyncResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class DownloadSingleTask {
private static final String TAG = "Download Task";
public AsyncResponse delegate = null;
private Context context;
private String downloadUrl;
public DownloadSingleTask(AsyncResponse asyncResponse, Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = ServerSettings.Main_URL + downloadUrl;
delegate = asyncResponse;
//Start Downloading Task
new DownloadSingleTask.DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<String, Integer, Void> {
private int PROGRESS_MAX = 100;
private int PROGRESS_CURRENT = 0;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
private int notificationID_;
private File apkStorage = null;
private File outputFile = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
notificationID_ = Application_shangvi.NotificationID.getID();
mBuilder = new NotificationCompat.Builder(context, "notify_001");
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadInProgress));
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setColor(context.getResources().getColor(R.color.colorLogo));
mBuilder.setOnlyAlertOnce(true);
mBuilder.setProgress(0, 0, true);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001", "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
}
@Override
protected void onPostExecute(Void result) {
try {
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
if (outputFile != null) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadCompleted));
mBuilder.setProgress(0, 0, false);
mNotificationManager.notify(notificationID_, mBuilder.build());
}
}, 2000);
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadAgain));
mBuilder.setProgress(0, 0, false);
mNotificationManager.notify(notificationID_, mBuilder.build());
}
}, 2000);
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() {
mBuilder.setContentTitle(context.getResources().getString(R.string.downloadAgain));
mBuilder.setProgress(0, 0, false);
mNotificationManager.notify(notificationID_, mBuilder.build());
}
}, 2000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
try {
delegate.processFinish(true);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
protected void onProgressUpdate(Integer... progress) {
mBuilder.setProgress(PROGRESS_MAX, progress[0], true);
// Displays the progress bar on notification
mNotificationManager.notify(notificationID_, mBuilder.build());
}
@Override
protected Void doInBackground(String... params) {
try {
Calendar calendar = Calendar.getInstance();
String date = fromInt(calendar.get(Calendar.MONTH))
+ fromInt(calendar.get(Calendar.DAY_OF_MONTH))
+ fromInt(calendar.get(Calendar.YEAR))
+ fromInt(calendar.get(Calendar.HOUR_OF_DAY))
+ fromInt(calendar.get(Calendar.MINUTE))
+ fromInt(calendar.get(Calendar.SECOND));
String[] subFileName = downloadUrl.split("/");
String downloadFileName = date.toString() + subFileName[subFileName.length - 1];
Log.e(TAG, downloadUrl);
Log.e(TAG, downloadFileName);
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//Open Url Connection
httpURLConnection.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
httpURLConnection.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + httpURLConnection.getResponseCode()
+ " " + httpURLConnection.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(Environment.getExternalStorageDirectory(), "/" + context.getResources().getString(R.string.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 = httpURLConnection.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
publishProgress(Math.min(PROGRESS_CURRENT * 10, 100));
PROGRESS_CURRENT++;
}
//Close all connection after doing task
fos.close();
is.close();
scanPhoto(context, outputFile.toString());
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
public static String fromInt(int val) {
return String.valueOf(val);
}
public static void scanPhoto(Context context, String imageFileName) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imageFileName);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
}
👉 Call this class :
ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
new DownloadSingleTask(new AsyncResponse() {
@Override
public void processFinish(Object output) throws UnsupportedEncodingException {
}
}, this, url);
} else {
Toast.makeText(Activity_Main.this, getResources().getString(R.string.NoInternet), Toast.LENGTH_LONG).show();
}
👉 strings.xml :
<string name="NoInternet">No Internet connection</string>
Comments
Post a Comment