de.thecamper.android.androidtools.UpdateChecker.java Source code

Java tutorial

Introduction

Here is the source code for de.thecamper.android.androidtools.UpdateChecker.java

Source

/*
 * Copyright 2014 Daniel Grothe
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.thecamper.android.androidtools;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

/**
 * Checks if there is an update of the app from the internet in an asynchronous
 * task
 * 
 * As param there is needed the URL of the version-file and the one of the app
 * to download There are needed the strings R.string.versionURL and
 * R.string.appURL
 * 
 * @author Daniel Grothe
 * 
 */
public class UpdateChecker extends AsyncTask<Void, Void, Boolean> {

    private Context context; // activity context for the display of notification
    // toasts

    private boolean showNoUpdateToast, buildNumberIncluded; // boolean if a
    // notification
    // toast is shown;
    // boolean if the
    // buildnumber is
    // included to the
    // filename

    // should be shown
    private String versionURL, appURL; // URL of the
    // version-file and
    // the apk

    /**
     * Constructor
     * 
     * @param context
     *            the context of the parent
     * @param versionURL
     *            the url of the version-file with the actual versionnumber in
     *            it
     * @param appURL
     *            the url of the app which is downloaded. If setting
     *            buildNumberIncluded to true, include a "#" into it which is
     *            later replaced by the versionnumber
     * @param showNoUpdateToast
     *            boolean if in the case of no available update a
     *            toast-notification is shown or not
     * @param buildNumberIncluded
     *            if the versionnumber is included in the appfilename
     */
    public UpdateChecker(Context context, String versionURL, String appURL, boolean showNoUpdateToast,
            boolean buildNumberIncluded) {
        this.context = context;
        this.versionURL = versionURL;
        this.appURL = appURL;
        this.showNoUpdateToast = showNoUpdateToast;
        this.buildNumberIncluded = buildNumberIncluded;
    }

    protected Boolean doInBackground(Void... params) {
        try {
            // get the version code from a Get-Request
            URL url = new URL(versionURL);
            URLConnection con = url.openConnection();
            InputStream is = con.getInputStream();
            String encoding = con.getContentEncoding();
            encoding = encoding == null ? "UTF-8" : encoding;
            int versionNumber = Integer.parseInt(IOUtils.toString(is, encoding));

            // if it is a newer version out there return true
            if (versionNumber > context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionCode) {
                if (buildNumberIncluded)
                    appURL = appURL.replace("#", String.valueOf(versionNumber));
                return true;
            } else
                return false;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return false;
    }

    protected void onPostExecute(Boolean b) {
        if (b)
            // show Alert to inform the user of the update
            showUpdateAlert();
        else if (showNoUpdateToast)
            // show a notification toast if the preference is set
            Toast.makeText(context, context.getString(R.string.updateNotAvailable), Toast.LENGTH_SHORT).show();
    }

    /**
     * show a AlertDialog to inform the user of the update and let him download
     * the new version of the app
     */
    public void showUpdateAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getString(R.string.updateTitle));
        builder.setMessage(context.getString(R.string.updateAvailable));
        builder.setCancelable(false);
        builder.setPositiveButton(context.getString(R.string.yes), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(appURL));
                context.startActivity(intent);
                ((Activity) context).finish();
            }
        });
        builder.setNegativeButton(context.getString(R.string.later), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}