Se si ha un'app sul proprio sito web e si vuole rendere aggiornabile:
2) In un file .txt si scrive l'ultima versione presente online, che poi viene letto dall'app.
Lo script dentro activity viene realizzato cosi':
// funzione 1
int v1 = getVersionCode(this);
// funzione 2(3)
String vers_online=downloadText();
int v2 = Integer.parseInt(vers_online);
// se la nuova versione è maggiore della vecchia
if(v2>v1) {
Intent updateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL/app.apk"));startActivity(updateIntent);}1) Metodo dentro la classe MyActivity (funzione 1):
public static int getVersionCode(Context context) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
return pi.versionCode;
} catch (PackageManager.NameNotFoundException ex) {}
return 0;
}
Che viene chiamata con:
int version = getVersionCode(this);2) Metodi dentro la classe MyActivityImportante: per connettersi a internet e scaricare i file bisogna settare i permessi su Manifest.xml con<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>Funzione che si connette col file txt.private InputStream openHttpConnection() throws IOException {InputStream in = null; int response = -1; URL url = new URL("http://www.miosito.com/file.txt"); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); // Log.e("Connection", "stop1"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { System.out.println("Eccezione: " + ex.getMessage()); throw new IOException("Error connecting"); } return in; }Funzione che scarica la stringa e la legge.private String downloadText() {int BUFFER_SIZE = 2000; InputStream in = null; try { in = openHttpConnection(); } catch (IOException e1) { return ""; } String str = ""; if (in != null) { InputStreamReader isr = new InputStreamReader(in); int charRead; char[] inputBuffer = new char[BUFFER_SIZE]; try { while ((charRead = isr.read(inputBuffer)) > 0) { String readString = String.copyValueOf(inputBuffer, 0, charRead); str += readString; inputBuffer = new char[BUFFER_SIZE]; } in.close(); } catch (IOException e) { return ""; } } return str; }