Check for Updates Once a Day in Android in Background
by Sasikumar[ Edit ] 2014-01-11 10:57:16
Check for Updates Once a Day in Android in Background
Following code checks for updates of the Application once a day in the background, if an update (higher version than current) is found, it opens a Dialog and asks the user to open the market to check for it.
public class Test extends Activity {
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.front);
mHandler = new Handler();
/* Get lastUpdateTime from SharedPreferences */
SharedPreferences prefs = getPreferences(0);
lastUpdateTime = prefs.getLong("lastUpdateTime", 0);
/* Check lastUpdateTime is within 24hrs */
if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System.currentTimeMillis()) {
/* Update the lastUpdateTime with currentTime */
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
/* Call the checkUpdate Thread to check for update */
checkUpdate.start();
}
}
/* checkUpdate Thread checks for Updates in the Background */
private Thread checkUpdate = new Thread() {
public void run() {
try {
/* updateURL should return the latest version avialbel for the Application */
URL updateURL = new URL("http://yourdomain.com/updateAvailable");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
final String s = new String(baf.toByteArray());
/* Get current Version Number */
int curVersion = getPackageManager().getPackageInfo("your.app.id", 0).versionCode;
int newVersion = Integer.valueOf(s);
/* Is a higher version than the current */
if (newVersion > curVersion) {
/* Post a Handler for the UI to pick up and open the Dialog */
mHandler.post(showUpdate);
}
} catch (Exception e) {
}
}
};
/* This Runnable creates a Dialog and asks the user to open the Market */
private Runnable showUpdate = new Runnable(){
public void run(){
new AlertDialog.Builder(Test.this)
.setIcon(R.drawable.icon)
.setTitle("Update Available")
.setMessage("An update for is available!nnOpen Android Market and see the details?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:your.app.id"));
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Cancel */
}
})
.show();
}
};
}