Skip to content

Instantly share code, notes, and snippets.

@MacoChave
Created June 4, 2016 20:50
Show Gist options
  • Save MacoChave/ec7f683a1a8dcb20d74a7c115c2adbe5 to your computer and use it in GitHub Desktop.
Save MacoChave/ec7f683a1a8dcb20d74a7c115c2adbe5 to your computer and use it in GitHub Desktop.
Código para una apk actualizable
public class Autoupdater {
//PARA EJECUTAR EL INSTALADOR
Context context;
//SE LLAMARA DESPUES DE ALGUN ASYNCTASK
Runnable listener;
//ENLACE DE TXT DE LA VERSION NUEVA
private static final String INFO_FILE = "URL VERSION.TXT"
//CODIGO DE VERSION ACTUAL
private int currentVersionCode;
//NOMBRE DE VERSION ACTUAL
private String currentVersionName;
//CODIGO DE VERSION NUEVA
private int latestVersionCode;
//NOMBRE DE VERSION NUEVA
private String currentVersionName;
//URL DE DESCARGA DE LA APLICACION
private String downloadURL;
//CONSTRUCTOR DE LA CLASE
public Autoupdater () {
this.context = context;
}
/*
METODO PARA INICIALIZAR EL OBJETO. LLAMAR PRIMERO Y EN UN HILO PROPIO
*/
private void getData () {
try{
//DATOS LOCALES
Log.d("AutoUpdater", "GetData");
PackageInfo pckginfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
currentVersionCode = pckginfo.VersionCode;
currentVersionName = pckginfo.VersionName;
//DATOS REMOTOS
String data = downloadHttp(new URL(INFO_FILE));
JSONObject json = new JSONObject(data);
latestVersionCode = json.getInt("versionCode");
latestVersionName = json.getString("versionName");
downloadURL = json.getString("downloadURL");
Log.d("AutoUpdate", "Datos obtenidos con exito");
} catch (JSONException e) {
Log.e("AutoUpdate", "Ha habido un error con el JASON", e);
} catch (PackageManager.NameNotFoundException e) {
Log.e("AutoUpdate", "Ha habido un error con el paquete", e);
} catch (IOException e) {
Log.e("AutoUpdate", "Ha habido un error con la descarga", e)
}
}
//COMPROBAR VERSION ACTUAL Y NUEVA
public boolean isNewVersionAvailable () {
return getLatestVersionCode() > getCurrentVersionCode();
}
/*-----------------------------------------
GETERS DE LOS DATOS DE LAS VERSIONES
-------------------------------------------
getCurrentVersionCode()
getCurrentVersionName()
getLatestVersionCode()
getLatestVersionName()
getDownloadURL()
*/
/*
METODO PARA DESCARGAR Y CONVERTIR EL ARCHIVO DE INFORMACION
*/
private static String downloadHttp (URL url) throws IOException {
//CONECTANDO
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(15*1000);
c.setUseCaches(false);
c.connect();
BufferedReader reader = new BufferedReader(new ImputStreamReader(c.getInputStream()));
StringBuilder stringBuilder = new StringBuider();
String line;
while ((line = reader.readLine()) != null) {
StringBuilder.append(line + "\n");
}
return stringBuilder.toString():
}
/*
PRIMER METODO A USAR. SE ENCARGA DE CONECTARSE AL SERVIDOR Y OBTENER LA INFORMACION DE LA ULTIMA VERSION DE LA APLICACION.
OnFinishRunnable: LISTENER EJECUTABLE AL FINALIZAR.
*/
public void DownloadData (Runnable OnFinishRunnable) {
this.listener = OnFinishRunnable;
//EJECUTA EL ASYNCTASK PARA BAJAR LOS DATOS
downloadedData.execute();
}
/*
SEGUNDO METODO A USAR. SE ENCARGA DE DESCARGAR E INSTALAR LA APLICACION. PREPARA A LA APLICACION PARA CERRARLA Y DESINSTALARLA
*/
public void InstallNewVersion (Runnable OnFinishRunnable) {
if (isNewVersionAvailable()) {
if (getDownloadURL() == "") return;
listener = OnFinishRunnable;
String params[] = {getDownloadURL()};
downloadInstaller.execute(params);
}
}
/*
OBJETO DE ASYNCTASK ENCARGADO DE DESCARGAR LA INFORMACION DEL SERVIDOR Y EJECUTAR EL LISTENER
*/
private AsynkTask downloaderData = new AsynkTask () {
@Override
protected Object doInBackground (Object[] objects) {
//LLAMA A GETDATA() PARA SETEAR VARIABLES
getData();
return null;
}
@Override
protected void onPostExecute (Object o) {
super.onPostExecute(o);
//DESPUES DE EJECUTAR EL CODIGO PRINCIPAL, SE EJECUTA EL LISTENER PARA HACER SABER AL HILO PRINCIPAL.
if (listener != null)listener.run();
listener = null;
}
};
/*
OBJETO DE ASYNCTASK ENCARGADO DE DESCARGAR E INSTALAR LA ULTIMA VERSION DE LA APLICACION.
*/
private AsyncTask<String, Integer, Intent> downloadInstaller = new AsyncTask<String, Integer, Intent>() {
@Override
Protected Intent doInBackground (String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
C.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "NOMBRE DE APLICACION.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
//APK DESCARGADO
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "NOMBRE DE APLICACION.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//RETURN INTENT;
} catch (IOException e) {
Log.e("Update error", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Intent intent) {
super.onPostExecute(intent);
if (listener != null)listener.run();
listener = null;
}
};
}
public class MainActivity extends Activity implements AlertDialog.OnClickListener {
private Autoupdater updater;
private RelativeLayout loadingPanel;
private Context context;
protected void onCreate (Bundle saved InstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
loadingPanel = (RelativeLayout) findViewById(R.id.loadingPanel);
//Esto sirve si la actualizacion no se realiza al principio. No es este caso.
//loadingPanel.setVisibility(View.GONE);
comenzarActualizacion();
} catch () {
Toast.makeText(this,ex.getMessage(),Toast.LENGTH_LONG)
}
}
private void comenzarActualizar(){
//Para tener el contexto mas a mano.
context = this;
//Creamos el Autoupdater.
updater = new Autoupdater(this);
//Ponemos a correr el ProgressBar.
loadingPanel.setVisibility(View.VISIBLE);
//Ejecutamos el primer metodo del Autoupdater.
updater.DownloadData(finishBackgroundDownload);
}
/**
* Codigo que se va a ejecutar una vez terminado de bajar los datos.
*/
private Runnable finishBackgroundDownload = new Runnable() {
@Override
public void run() {
//Volvemos el ProgressBar a invisible.
loadingPanel.setVisibility(View.GONE);
//Comprueba que halla nueva versión.
if (updater.isNewVersionAvailable()) {
//Crea mensaje con datos de versión.
String msj = "Nueva Version: " + updater.isNewVersionAvailable();
msj += "\nCurrent Version: " + updater.getCurrentVersionName() + "(" + updater.getCurrentVersionCode() + ")";
msj += "\nLastest Version: " + updater.getLatestVersionName() + "(" + updater.getLatestVersionCode() +")";
msj += "\nDesea Actualizar?";
//Crea ventana de alerta.
AlertDialog.Builder dialog1 = new AlertDialog.Builder(context);
dialog1.setMessage(msj);
dialog1.setNegativeButton(R.string.cancel, null);
//Establece el boton de Aceptar y que hacer si se selecciona.
dialog1.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Vuelve a poner el ProgressBar mientras se baja e instala.
loadingPanel.setVisibility(View.VISIBLE);
//Se ejecuta el Autoupdater con la orden de instalar. Se puede poner un listener o no
updater.InstallNewVersion(null);
}
});
//Muestra la ventana esperando respuesta.
dialog1.show();
} else {
//No existen Actualizaciones.
Log.d("No Hay actualizaciones");
}
}
};
}
<RelativeLayout
android:id = "@+id/loadingPanel"
android:layout_width = "mach_parent"
android:layout_heigth = "wrap_content"
android:gravity = "center" >
<ProgressBar
android:layout_width = "wrap_content"
android:layout_heigth = "wrap_content"
android:indeterminate = "true" />
</RelativeLayout>
<!--EN ANDROID MANIFEST-->
<!--URL APK: https://drive.google.com/uc?export=download&id=[CODIGO ID DEL ARCHIVO]-->
<usses-permission android:name="android.permission.INTERNET" />
<usses-permission android.name="android.permission.WRITE_EXTERNAL_STORAGE" />
{
"versionCode":1,
"versionName":0.1,
"downloadURL":"URL DEL APK"
}
@MacoChave
Copy link
Author

Para iniciar la actualización de una apk, basta con llamar al método comenzarActualizacion().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment