如何让用户从应用程序内部检查最新的应用程序版本?

问题描述 投票:0回答:12

我想在应用程序中添加一个“检查更新”按钮,以便当有人单击它时,它将显示一条 toast 消息/进度对话框以检查应用程序的版本。

如果发现新版本,应用程序将自动将其下载到手机并让用户手动安装更新的应用程序。

或者任何其他方法都可以,只要它可以检查最新版本并通知用户更新即可。


更新:现在您可以使用 https://developer.android.com/guide/playcore/in-app-updates

在应用程序中执行此操作
java android http versioning
12个回答
41
投票

您可以使用此 Android 库:https://github.com/danielemaddaluno/Android-Update-Checker。它的目的是提供一个可重用的工具来异步检查应用程序商店中是否存在任何较新发布的更新。 它基于使用 Jsoup (http://jsoup.org/) 来测试解析 Google Play 商店上的应用程序页面是否确实存在新更新:

private boolean web_update(){
    try {       
        String curVersion = applicationContext.getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, 0).versionName;   
        String newVersion = curVersion;
        newVersion = 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()
                .select("div[itemprop=softwareVersion]")
                .first()
                .ownText();
        return (value(curVersion) < value(newVersion)) ? true : false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

并且作为“值”函数如下(如果值在 0-99 之间则有效):

private long value(String string) {
    string = string.trim();
    if( string.contains( "." )){ 
        final int index = string.lastIndexOf( "." );
        return value( string.substring( 0, index ))* 100 + value( string.substring( index + 1 )); 
    }
    else {
        return Long.valueOf( string ); 
    }
}

如果您只想验证版本之间的不匹配,您可以更改:

value(curVersion) < value(newVersion)
value(curVersion) != value(newVersion)


26
投票

如果它是市场上的应用程序,则在应用程序启动时,激发一个 Intent 以打开市场应用程序,希望这会导致它检查更新。

否则实施和更新检查器相当容易。这是我的代码(大致):

String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
                                                 // should send the current version
                                                 // to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));

当然,您应该重写此代码以在后台线程上执行请求,但您明白了。

如果您喜欢稍微复杂一点但允许您的应用程序 自动应用更新请参阅此处


20
投票

Google 两个月前更新了 Play 商店。 这是现在对我有用的解决方案..

class GetVersionCode extends AsyncTask<Void, String, String> {

    @Override

    protected String doInBackground(Void... voids) {

        String newVersion = null;

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName()  + "&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;

    }


    @Override

    protected void onPostExecute(String onlineVersion) {

        super.onPostExecute(onlineVersion);

        if (onlineVersion != null && !onlineVersion.isEmpty()) {

            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show anything
            }

        }

        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);

    }
}

不要忘记添加 JSoup 库

dependencies {
compile 'org.jsoup:jsoup:1.8.3'}

以及 Oncreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String currentVersion;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    new GetVersionCode().execute();

}

就是这样.. 感谢此链接


5
投票

compile 'org.jsoup:jsoup:1.10.2'
添加到 APP LEVEL build.gradle

中的依赖项

&

只需添加以下代码即可开始。

private class GetVersionCode extends AsyncTask<Void, String, String> {
    @Override
    protected String doInBackground(Void... voids) {

        try {
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + SplashActivity.this.getPackageName() + "&hl=it")
                    .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()
                    .select("div[itemprop=softwareVersion]")
                    .first()
                    .ownText();
            return newVersion;
        } catch (Exception e) {
            return newVersion;
        }
    }

    @Override
    protected void onPostExecute(String onlineVersion) {
        super.onPostExecute(onlineVersion);

        if (!currentVersion.equalsIgnoreCase(onlineVersion)) {
            //show dialog
            new AlertDialog.Builder(context)
                    .setTitle("Updated app available!")
                    .setMessage("Want to update app?")
                    .setPositiveButton("Update", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                            final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
                            try {
                                Toast.makeText(getApplicationContext(), "App is in BETA version cannot update", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                            } catch (ActivityNotFoundException anfe) {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                            }
                        }
                    })
                    .setNegativeButton("Later", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                            dialog.dismiss();
                            new MyAsyncTask().execute();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

        }
    }
}

5
投票

导航至您的游戏页面:

https://play.google.com/store/apps/details?id=com.yourpackage

使用标准 HTTP GET。 现在,以下 jQuery 会为您找到重要信息:

当前版本

$("[itemprop='softwareVersion']").text()

有什么新鲜事

$(".recent-change").each(function() { all += $(this).text() + "\n"; })

现在您可以手动提取这些信息,只需在您的应用程序中创建一个方法来为您执行此操作。

public static String[] getAppVersionInfo(String playUrl) {
    HtmlCleaner cleaner = new HtmlCleaner();
    CleanerProperties props = cleaner.getProperties();
    props.setAllowHtmlInsideAttributes(true);
    props.setAllowMultiWordAttributes(true);
    props.setRecognizeUnicodeChars(true);
    props.setOmitComments(true);
    try {
        URL url = new URL(playUrl);
        URLConnection conn = url.openConnection();
        TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
        Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
        Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");

        String version = "", whatsNew = "";
        for (Object new_node : new_nodes) {
            TagNode info_node = (TagNode) new_node;
            whatsNew += info_node.getAllChildren().get(0).toString().trim()
                    + "\n";
        }
        if (version_nodes.length > 0) {
            TagNode ver = (TagNode) version_nodes[0];
            version = ver.getAllChildren().get(0).toString().trim();
        }
        return new String[]{version, whatsNew};
    } catch (IOException | XPatherException e) {
        e.printStackTrace();
        return null;
    }
}

使用HtmlCleaner


2
投票

没有这方面的API,你不能自动安装它,你可以将他们重定向到它的市场页面,以便他们可以升级。您可以将最新版本保存在 Web 服务器上的文件中,并让应用程序检查它。这是此方法的一种实现:

http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp


1
投票

我确实使用了应用内更新。这仅适用于运行 Android 5.0(API 级别 21)或更高版本的设备,


1
投票

以下是查找当前和最新可用版本的方法:

       try {
            String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            String newVersion = curVersion;
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&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()
                    .select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
                    .first()
                    .ownText();
            Log.d("Curr Version" , curVersion);
            Log.d("New Version" , newVersion);

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

0
投票

您应该先查看市场上的应用程序版本,并将其与设备上的应用程序版本进行比较。如果它们不同,则可能有可用更新。在这篇文章中,我写下了获取当前市场版本和设备上当前版本的代码,并将它们放在一起进行比较。我还展示了如何显示更新对话框并将用户重定向到更新页面。请访问此链接:https://stackoverflow.com/a/33925032/5475941


0
投票

我知道OP很旧,当时应用内更新不可用。 但从 API 21 开始,您可以使用应用内更新检查。 您可能需要留意一些写得很好的要点here:


0
投票

使用jsoup HTML解析器库@ https://jsoup.org/

implementation 'org.jsoup:jsoup:1.13.1'

您可以简单地为此创建一个方法;

private void IsUpdateAvailable() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            String newversion = "no";
            String newversiondot = "no";
            try {
                newversiondot = 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().select("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
                        .first()
                        .ownText();

                newversion = newversiondot.replaceAll("[^0-9]", "");

            } catch (IOException e) {
                Log.d("TAG NEW", "run: " + e);
            }

            final String finalNewversion = newversion;
            final String finalNewversiondot = newversiondot;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (Integer.parseInt(finalNewversion) > Integer.parseInt(getApplicationContext().getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, 0).versionName.replaceAll("[^0-9]", ""))) {
                            showDialog(UsersActivity.this, "Version: "+finalNewversiondot);
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }).start();
}

0
投票

我们可以通过添加这些代码来检查更新:

首先我们需要添加依赖项:

实现“org.jsoup:jsoup:1.10.2”

其次我们需要创建Java文件:

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

import org.jsoup.Jsoup;

public class CurrentVersion{
    private Activity activity;
    public CurrentVersion(Activity activity) {
        this.activity = activity;
    }
    //current version of app installed in the device
private String getCurrentVersion(){
        PackageManager pm = activity.getPackageManager();
        PackageInfo pInfo = null;
        try {
        pInfo = pm.getPackageInfo(activity.getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e1) {
        e1.printStackTrace();
        }
        return pInfo.versionName;
        }
private class GetLatestVersion extends AsyncTask<String, String, String> {
    private String latestVersion;
    private ProgressDialog progressDialog;
    private boolean manualCheck;
    GetLatestVersion(boolean manualCheck) {
        this.manualCheck = manualCheck;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (manualCheck)
        {
            if (progressDialog!=null)
            {
                if (progressDialog.isShowing())
                {
                    progressDialog.dismiss();
                }
            }
        }
        String currentVersion = getCurrentVersion();
        //If the versions are not the same
        if(!currentVersion.equals(latestVersion)&&latestVersion!=null){
            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("An Update is Available");
            builder.setMessage("Its better to update now");
            builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Click button action
                    activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+activity.getPackageName())));
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.show();
        }
        else {
            if (manualCheck) {
                Toast.makeText(activity, "No Update Available", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            //It retrieves the latest version by scraping the content of current version from play store at runtime
            latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + activity.getPackageName() + "&hl=it")
                    .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()
                    .select(".hAyfc .htlgb")
                    .get(7)
                    .ownText();
            return latestVersion;
        } catch (Exception e) {
            return latestVersion;
        }
    }
}
    public void checkForUpdate(boolean manualCheck)
    {
        new GetLatestVersion(manualCheck).execute();
    }
}

第三,我们需要在您想要显示更新的主类中添加此类:

AppUpdateChecker appUpdateChecker=new AppUpdateChecker(this); 
appUpdateChecker.checkForUpdate(false);

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.