Skip to content

Instantly share code, notes, and snippets.

@faridfor
Created March 7, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faridfor/4050711c0fd44ca452e5d3126c13852a to your computer and use it in GitHub Desktop.
Save faridfor/4050711c0fd44ca452e5d3126c13852a to your computer and use it in GitHub Desktop.
package ir.adanic.kilid.tasks;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.PowerManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import ir.adanic.kilid.BuildConfig;
import ir.adanic.kilid.R;
import ir.adanic.kilid.utils.Logger;
public class UpdateTask extends AsyncTask<String, Integer, Object> {
public static final String TAG = UpdateTask.class.getName();
private static final String NEW_APK_NAME = "newKeyleed.apk";
private final WeakReference<Context> mContextWeakReference;
@NonNull
private final DownloadTaskInterface mDownloadTaskInterface;
private PowerManager.WakeLock mWakeLock;
private ProgressDialog mProgressDialog;
public UpdateTask(Context context, @NonNull DownloadTaskInterface downloadTaskInterface) {
mContextWeakReference = new WeakReference<>(context);
mDownloadTaskInterface = downloadTaskInterface;
}
@SuppressLint("WorldReadableFiles")
@Override
protected Object doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
Context context = mContextWeakReference.get();
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
int fileLength = connection.getContentLength();
input = connection.getInputStream();
// String fileName = getFileStreamPath(NEW_APK_NAME).getPath();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File path = new File(context.getFilesDir(), "external_files");
//noinspection ResultOfMethodCallIgnored
path.mkdirs();
File newFile = new File(path, NEW_APK_NAME);
output = new FileOutputStream(newFile);
} else try {
//noinspection deprecation
output = context.openFileOutput(NEW_APK_NAME, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
Logger.e(e);
}
byte[] data = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0)
publishProgress((int) (total * 100 / fileLength));
//noinspection ConstantConditions
output.write(data, 0, count);
}
} catch (Exception e) {
return e;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException e) {
if (BuildConfig.DEBUG)
Logger.e(TAG, e.getMessage(), e);
}
if (connection != null)
connection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Context context = mContextWeakReference.get();
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(context.getString(R.string.downloading_update_message));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setOnCancelListener(dialog -> cancel(true));
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm != null) {
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire(600000);
}
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Object object) {
Context context = mContextWeakReference.get();
try {
mWakeLock.release();
} catch (Exception ignored) {
}
mProgressDialog.dismiss();
if (object != null) {
if (object instanceof Exception)
mDownloadTaskInterface.onDownloadFail((Exception) object);
} else {
Toast.makeText(context, context.getString(R.string.update_complete), Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File path = new File(context.getFilesDir(), "external_files");
File newFile = new File(path, NEW_APK_NAME);
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", newFile);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
context.grantUriPermission("com.android.packageinstaller", apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
mDownloadTaskInterface.onDownloadFinish();
} else {
Uri uri = Uri.fromFile(context.getFileStreamPath(NEW_APK_NAME));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
mDownloadTaskInterface.onDownloadFinish();
}
}
}
public interface DownloadTaskInterface {
void onDownloadFinish();
void onDownloadFail(Exception e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment