tsurutanのつぶやき

備忘録としてつぶやきます

Android 強制アップデートの実装方法

f:id:tsurutan:20161007144504p:plain

今回はAndroidアプリの強制アップデートの方法について説明したいと思います。

現在リリースされているアプリケーションで致命的なバグを見つけた時、すぐにでもそのバグを取り除きたいですよね?

でも、Androidで自動アップデートを設定していない人だと、アプリケーションが更新されたことに気づかない人が多いです。

このようなケースを対処するためにAndroidの最新バージョンを確認し、強制アップデートをする方法について説明したいと思います。

実装

まずは、現在使用しているアプリケーションのバージョンを取得します。

PackageManager pm = mContext.getPackageManager();
        PackageInfo pInfo = null;

        try {
            pInfo = pm.getPackageInfo(mContext.getPackageName(), 0);

        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        mCurrentVersion = pInfo.versionName;

そして次に最新バージョンの値を取得するのですが、一々独自サーバーで管理するのは面倒くさいのでGoogle play storeの公式ページから引っ張てきちゃいましょう。

ここでGoogle play storeのhtmlを処理するのでJsoupというライブラリーをインポートしてください。

Jsoupの使い方については次回の記事で説明したいと思います。

                Document doc = Jsoup.connect(mContext.getString(R.string.play_store_url)).get();
                mLatestVersion = doc.getElementsByAttributeValue
                        ("itemprop", "softwareVersion").first().text();

Jsoupconnectには公開しているアプリのurlを渡してください。

Play storeのhtmlを見るとわかると思うのですが

f:id:tsurutan:20161007143614p:plain

itempropsoftwareVersionとなっているタグの中にバージョンが記述されていますね。

それをdoc.getElementsByAttributeValue("itemprop", "softwareVersion").first().text()を使って取ってきているのです。

また、これはapi通信を行っているので非同期処理を行わなくてはいけません。

AsyncTaskなどを拡張したクラスの中で記述しましょう。

そして、最新バージョンを取得できたので現在のバージョンと比較します。

int latestVersion = Integer.valueOf(mLatestVersion.split("\\.")[1]);
                int currentVersion = Integer.valueOf(mCurrentVersion.split("\\.")[1]);
                Log.d("TEST", "Current Version " + currentVersion + " Latest Version " + latestVersion);
                if (latestVersion > currentVersion) {
                    showUpdateDialog();
                }

このコードではマイナーバージョンを比較しており、例えば1.0.01.1.0になった時にダイアログを表示するようにしております。

あとは表示するダイアログのcancelablefalseにすれば完成です。

一応全体のコードを載せておきますね。

public class UpdateChecker {
    private String mCurrentVersion;
    private String mLatestVersion;
    private Context mContext;
    private AppCompatActivity mActivity;

    @Inject
    public UpdateChecker(Context context) {
        mContext = context;
    }

    public void checkUpdate(AppCompatActivity activity) {
        mActivity = activity;
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pInfo = null;

        try {
            pInfo = pm.getPackageInfo(mContext.getPackageName(), 0);

        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        mCurrentVersion = pInfo.versionName;

        new GetLatestVersion().execute();
    }

    private class GetLatestVersion extends AsyncTask<String, String, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            try {
                Document doc = Jsoup.connect(mContext.getString(R.string.play_store_url)).get();
                mLatestVersion = doc.getElementsByAttributeValue
                        ("itemprop", "softwareVersion").first().text();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return new JSONObject();
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if (mLatestVersion != null) {
                int latestVersion = Integer.valueOf(mLatestVersion.split("\\.")[1]);
                int currentVersion = Integer.valueOf(mCurrentVersion.split("\\.")[1]);
                Log.d("TEST", "Current Version " + currentVersion + " Latest Version " + latestVersion);
                if (latestVersion > currentVersion) {
                    showUpdateDialog();
                }
            }
            super.onPostExecute(jsonObject);
        }
    }

    private void showUpdateDialog() {
        MaterialDialog.Builder materialDialog = new MaterialDialog.Builder(mActivity);
        materialDialog.cancelable(false);
        materialDialog
                .title(mContext.getString(R.string.update_title))
                .positiveText(mContext.getString(R.string.update))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
                                (mContext.getString(R.string.play_store_intent_url))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        mActivity.finish();
                        dialog.dismiss();
                    }
                })
                .show();
    }
}

オススメ記事

www.tsurutan.com

www.tsurutan.com

www.tsurutan.com

超初心者でも大丈夫! はじめてのAndroidプログラミング Android Studio 2対応

超初心者でも大丈夫! はじめてのAndroidプログラミング Android Studio 2対応

Effective Modern C++ ―C++11/14プログラムを進化させる42項目

Effective Modern C++ ―C++11/14プログラムを進化させる42項目