我想在应用中添加“检查更新”按钮,以便当有人点击它时,它会显示一个Toast消息/进度对话框,用于检查应用的版本。
如果找到新版本,应用会自动将其下载到手机,并允许用户手动安装更新的应用。
或其他任何方法都可以,只要它可以检查最新版本并通知用户更新。
答案 0 :(得分:43)
为了节省用于检查Android应用程序新版本更新的时间,我将其写为库和开源https://github.com/winsontan520/Android-WVersionManager
答案 1 :(得分:36)
您可以使用此Android库:https://github.com/danielemaddaluno/Android-Update-Checker。它旨在提供一种可重复使用的工具,以便在商店中存在应用程序的任何较新发布更新时异步检查。 它基于使用Jsoup(http://jsoup.org/)来测试是否确实存在解析Google Play商店中的应用页面的新更新:
private boolean web_update(){
try {
String curVersion = applicationContext.getPackageManager().getPackageInfo(package_name, 0).versionName;
String newVersion = curVersion;
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + package_name + "&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)
答案 2 :(得分:26)
如果它是市场上的应用程序,那么在应用程序启动时,启动Intent以打开Market应用程序,这将导致它检查更新。
否则实现和更新检查器相当容易。这是我的代码(大致):
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")));
当然你应该重写这个来在后台线程上做请求,但你明白了。
如果你喜欢一些但更复杂的东西,但允许你的应用 自动应用更新,请参阅here。
答案 3 :(得分:9)
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();
}
那是...... 感谢this link
答案 4 :(得分: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;
}
}
答案 5 :(得分:4)
将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();
}
}
}
答案 6 :(得分:2)
没有这方面的API,您无法自动安装它,您可以将它们重定向到它的市场页面,以便它们可以升级。您可以将最新版本放在Web服务器上的文件中,然后让应用程序对其进行检查。这是一个实现:
http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp
答案 7 :(得分:1)
以下是查找当前和最新可用版本的方法:
http://localhost:8444/pac4j1
答案 8 :(得分:0)
您应首先检查市场上的应用版本,并将其与设备上的应用版本进行比较。如果它们不同,则可能是可用的更新。在这篇文章中,我写下了在设备上获取当前版本的市场和当前版本的代码,并将它们进行比较。我还展示了如何显示更新对话框并将用户重定向到更新页面。请访问此链接:https://stackoverflow.com/a/33925032/5475941
答案 9 :(得分:0)
我确实使用过in-app updates。仅适用于运行Android 5.0(API级别21)或更高版本的设备,
答案 10 :(得分:0)
我知道OP很旧,那时in-app-update不可用。 但是从API 21开始,您可以使用应用内更新检查。 您可能需要注意here写得很好的一些观点:
答案 11 :(得分: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);
我希望它将为您提供帮助
答案 12 :(得分: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();
}