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

本文介绍如何在Android应用中获取并比较Google Play上的最新版本,以实现自动更新功能。首先,需要添加jsoup依赖,然后创建一个VersionChecker工具类,通过这个类可以检查Google Play上的版本信息,从而决定是否提示用户更新应用。

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();
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值