当新版本可用时,Android 以编程方式更新应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22709443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android programmatically update application when a new version is available
提问by user2914699
Within my application, I want to check if there is any updated version of my application is in the app store. If there is any, then have to inform the user through an alert message and if he/she opt for upgrade I want to update the new version.I want to do all this through my application. Is this possible?
在我的应用程序中,我想检查应用程序商店中是否有我的应用程序的任何更新版本。如果有,则必须通过警报消息通知用户,如果他/她选择升级,我想更新新版本。我想通过我的应用程序完成所有这些。这可能吗?
回答by Ahmad Arslan
I have the same issue but it resolved by JSOUP library. Here is the library download link: http://jsoup.org/download
我有同样的问题,但它由 JSOUP 库解决。这是库下载链接:http: //jsoup.org/download
String 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();
Log.e("new Version", newVersion);
回答by grunk
Google does not provide any API for that.
Google 没有为此提供任何 API。
Nevertheless , you can make an http request on the web version of the playstore (https://play.google.com/store/apps/details?id=your.namespace)
不过,您可以在 Playstore 的网络版本 ( https://play.google.com/store/apps/details?id=your.namespace)上发出 http 请求
To make the request you can use DefaultHttpClient
要发出请求,您可以使用DefaultHttpClient
Once you get the page content you should parse it (jsoupis a good solution) and search for :
获得页面内容后,您应该对其进行解析(jsoup是一个很好的解决方案)并搜索:
<div class="content" itemprop="softwareVersion"> 2.2.0 </div>
Once you find this part of the page , you can extract the version number and compare it with the one available in your app :
找到页面的这一部分后,您可以提取版本号并将其与应用程序中可用的版本号进行比较:
try
{
String version = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
if( ! version.equals(versionFromHTML))
{
Toast.makeText(this, "New version available on play store", Toast.LENGTH_SHORT);
}
}
catch (NameNotFoundException e)
{
//No version do something
}
For the HTML parsing part , have a look here
对于 HTML 解析部分,请看这里
Keep in mind that everybody won't see the new version in the same time. It could take time to be propagated (probably because of cache).
请记住,每个人都不会同时看到新版本。传播可能需要时间(可能是因为缓存)。
回答by GabrielOshiro
EDIT
编辑
They have recently changed Google play website and now this code is broken. Avoid this solution or be ready to patch your app whenever Google Play pages change.
他们最近更改了 Google Play 网站,现在此代码已损坏。避免使用此解决方案或准备在 Google Play 页面更改时修补您的应用程序。
Ahmad Arlan's answeris the best answer so far. But if you got here and you try to cut and paste his code you'll go through the same issues I just had, so I might as well just post it here to help others like me.
Ahmad Arlan 的答案是迄今为止最好的答案。但是如果你来到这里并尝试剪切和粘贴他的代码,你会遇到我刚刚遇到的同样问题,所以我不妨把它贴在这里以帮助像我这样的人。
Make sure you have
INTERNET
permission on yourAndroidManifest.xml
file.<uses-permission android:name="android.permission.INTERNET"/>
Add
JSOUP
dependency to your modulebuild.gradle
.dependencies { compile 'org.jsoup:jsoup:1.10.2' }
Surround the snippet with
try and catch
and don't run it on the main thread.public class MainActivity extends AppCompatActivity { String newVersion; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new FetchAppVersionFromGooglePlayStore().execute(); } class FetchAppVersionFromGooglePlayStore extends AsyncTask<String, Void, String> { protected String doInBackground(String... urls) { try { return Jsoup.connect("https://play.google.com/store/apps/details?id=" + "com.directed.android.smartstart" + "&hl=en") .timeout(10000) .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(); } catch (Exception e) { return ""; } } protected void onPostExecute(String string) { newVersion = string; Log.d("new Version", newVersion); } } }
确保您
INTERNET
对AndroidManifest.xml
文件有权限。<uses-permission android:name="android.permission.INTERNET"/>
JSOUP
为您的模块添加依赖项build.gradle
。dependencies { compile 'org.jsoup:jsoup:1.10.2' }
用 包围代码片段,
try and catch
不要在主线程上运行它。public class MainActivity extends AppCompatActivity { String newVersion; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new FetchAppVersionFromGooglePlayStore().execute(); } class FetchAppVersionFromGooglePlayStore extends AsyncTask<String, Void, String> { protected String doInBackground(String... urls) { try { return Jsoup.connect("https://play.google.com/store/apps/details?id=" + "com.directed.android.smartstart" + "&hl=en") .timeout(10000) .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(); } catch (Exception e) { return ""; } } protected void onPostExecute(String string) { newVersion = string; Log.d("new Version", newVersion); } } }
I posted a copy here of the project on github.
我在github上发布了该项目的副本。
回答by Nbn
This worked for me. Add this dependency.
这对我有用。添加此依赖项。
implementation 'org.jsoup:jsoup:1.8.3'
At onCreate() method use the following code:
在 onCreate() 方法中使用以下代码:
try {
String currentVersion="";
currentVersion = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
Log.e("Current Version","::"+currentVersion);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
new GetVersionCode().execute();
Create class GetVersionCode:
创建类 GetVersionCode:
private 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=" + context.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 (onlineVersion.equals(currentVersion)) {
} else {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Update");
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage("New Update is available");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Update", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName())));
}
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
}
}
回答by Anoop M
You can use the Play Core Library In-app updates to tackle this. You can check for update availabilityand install themif available seamlessly.
您可以使用 Play 核心库应用内更新来解决此问题。您可以检查更新可用性并安装它们(如果可用)。
Note that, In-app updates works only with devices running Android 5.0 (API level 21) or higher, and requires you to use Play Core library1.5.0 or higher.
请注意,应用内更新仅适用于运行 Android 5.0(API 级别 21)或更高版本的设备,并且需要您使用Play Core 库1.5.0 或更高版本。
In-app updates are not compatible with apps that use APK expansion files (.obb files). You can either go for flexible downloadsor immediate updateswhich Google Play takes care of downloading and installing the update for you.
应用内更新与使用 APK 扩展文件(.obb 文件)的应用不兼容。您可以选择灵活下载或立即更新,由 Google Play 负责为您下载和安装更新。
dependencies {
implementation 'com.google.android.play:core:1.5.0'
...
}
回答by Code-Apprentice
Google Play already does this. When you upload a new version of your app, it will either send an alert directly to your users' devices or download the upgrade automatically if the user has this option turned on in the Google Play app.
Google Play 已经这样做了。当您上传应用的新版本时,它会直接向您用户的设备发送警报,或者如果用户在 Google Play 应用中启用了此选项,则会自动下载升级。
回答by cksagar
private void checkForUpdate() {
PackageInfo packageInfo = null;
try { packageInfo=getPackageManager().getPackageInfo(DashboardActivity.this.getPackageName(), 0);
int curVersionCode = packageInfo.versionCode
if (curVersionCode > 1) { // instead of one use value get from server for the new update.
showUpdateDialog();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
回答by Salmaan
Well there is another way I figured out and this is how I am doing it.
好吧,我想出了另一种方法,这就是我的做法。
HttpPost httppostUserName = new HttpPost("https://androidquery.appspot.com/api/market?app=com.supercell.clashofclans"); //your package name
HttpClient httpclient = new DefaultHttpClient();
HttpResponse responseUser = httpclient.execute(httppostUserName);
String responseStringUser = EntityUtils.toString(responseUser.getEntity(), HTTP.UTF_8);
Log.d(Constants.TAG, "Response: " + responseStringUser);
try {
JSONObject Json = new JSONObject(responseStringUser);
newVersion = Json.getString("version");
} catch (Exception e) {
e.printStackTrace();
}
You will get a clearer view if you paste the url in your browser to see the results.
如果您将 url 粘贴到浏览器中以查看结果,您将获得更清晰的视图。