Android :从Google play 获取当前APP 版本号

APP自动更新 可以从服务器下载更新,也可以跳转商店更新,今天说的是获取当前应用在Google play中的最新版本和本地版本比较,判断是否需要更新。

1 添加依赖

implementation 'org.jsoup:jsoup:1.10.2'

如果依赖包导入失败 可以改成 1.5.2
或者手动下载 https://jar-download.com/artifacts/org.jsoup/jsoup/1.10.2/source-code

2 创建工具类 VersionChecker

public class VersionChecker extends AsyncTask<String, String, String> {

     private String newVersion;

    @Override
    protected String doInBackground(String... params) {

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get();
            if (document != null) {
                Elements element = document.getElementsContainingOwnText("Current Version");
                for (Element ele : element) {
                    if (ele.siblingElements() != null) {
                        Elements sibElemets = ele.siblingElements();
                        for (Element sibElemet : sibElemets) {
                            newVersion = sibElemet.text();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;
    }
}

3 使用:

VersionChecker versionChecker = new VersionChecker();
try {
     mLatestVersionName = versionChecker.execute().get();
     if (Double.parseDouble(BuildConfig.VERSION_NAME) < Double.parseDouble(mLatestVersionName)) {
      //perform your task here like show alert dialogue "Need to upgrade app"
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setData(Uri.parse("market://details?id=" + this.getPackageName()));
      if (intent.resolveActivity(getPackageManager()) != null) { //可以接收 
        startActivity(intent); 
      } else { //没有应用市场,我们通过浏览器跳转到Google Play 
        intent.setData(Uri.parse(“https://play.google.com/store/apps/details?id=” + this.getPackageName())); 
        startActivity(intent);
      }
} catch (InterruptedException | ExecutionException e) {
     e.printStackTrace();
}

你可能感兴趣的:(Android :从Google play 获取当前APP 版本号)