我如何从谷歌游戏商店获取应用程序版本信息,以便在更新游戏商店应用程序时提示用户强制/推荐更新应用程序,即在用户使用旧版本应用程序的情况下。我已经通过andorid-market-api这不是官方的方式,也需要谷歌的oauth login身份验证。我也经历了android query,提供应用内版本检查,但它不适用于我的情况。我找到了以下两种选择:
还有其他方法可以轻松完成吗?
我建议不要使用库只创建一个新类
1.
public class VersionChecker extends AsyncTask<String, String, String>{
String newVersion;
@Override
protected String doInBackground(String... params) {
try {
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.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
.first()
.ownText();
} catch (IOException e) {
e.printStackTrace();
}
return newVersion;
}
VersionChecker versionChecker = new VersionChecker();
String latestVersion = versionChecker.execute().get();
就这些
最简单的方法是使用谷歌的firebase软件包,并使用新版本的远程通知或实时配置,并将id发送给低于版本号的用户查看更多String packageName = "com.google.android.apps.plus";
String url = "http://carreto.pt/tools/android-store-version/?package=";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url+packageName, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
/*
here you have access to:
package_name, - the app package name
status - success (true) of the request or not (false)
author - the app author
app_name - the app name on the store
locale - the locale defined by default for the app
publish_date - the date when the update was published
version - the version on the store
last_version_description - the update text description
*/
try{
if(response != null && response.has("status") && response.getBoolean("status") && response.has("version")){
Toast.makeText(getApplicationContext(), response.getString("version").toString(), Toast.LENGTH_LONG).show();
}
else{
//TODO handling error
}
}
catch (Exception e){
//TODO handling error
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//TODO handling error
}
});
这里的好处是你可以检查版本号而不是名称,这应该更方便:)另一方面 - 你应该在发布后每次都在api / firebase中更新版本。
okHttp
使用Jquery
private fun getVersion(onChecked: OnChecked, packageName: String) {
Thread {
try {
val httpGet = HttpGet("https://play.google.com/store/apps/details?id="
+ packageName + "&hl=it")
val response: HttpResponse
val httpParameters = BasicHttpParams()
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000)
HttpConnectionParams.setSoTimeout(httpParameters, 10000)
val httpclient = DefaultHttpClient(httpParameters)
response = httpclient.execute(httpGet)
val entity = response.entity
val `is`: InputStream
`is` = entity.content
val reader: BufferedReader
reader = BufferedReader(InputStreamReader(`is`, "iso-8859-1"), 8)
val sb = StringBuilder()
var line: String? = null
while ({ line = reader.readLine(); line }() != null) {
sb.append(line).append("\n")
}
val resString = sb.toString()
var index = resString.indexOf(MATCHER)
index += MATCHER.length
val ver = resString.substring(index, index + 6) //6 is version length
`is`.close()
onChecked.versionUpdated(ver)
return@Thread
} catch (ignore: Error) {
} catch (ignore: Exception) {
}
onChecked.versionUpdated(null)
}.start()
}
这是jQuery版本,以获取版本号,如果其他人需要它。
$.get("https://play.google.com/store/apps/details?id=" + packageName + "&hl=en", function(data){
console.log($('<div/>').html(data).contents().find('div[itemprop="softwareVersion"]').text().trim());
});
使用此代码完美正常工作。
public void forceUpdate(){
PackageManager packageManager = this.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo =packageManager.getPackageInfo(getPackageName(),0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String currentVersion = packageInfo.versionName;
new ForceUpdateAsync(currentVersion,TodayWork.this).execute();
}
public class ForceUpdateAsync extends AsyncTask<String, String, JSONObject> {
private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
this.currentVersion = currentVersion;
this.context = context;
}
@Override
protected JSONObject doInBackground(String... params) {
try {
latestVersion = 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()
.select("div.hAyfc:nth-child(3) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
.first()
.ownText();
Log.e("latestversion","---"+latestVersion);
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null){
if(!currentVersion.equalsIgnoreCase(latestVersion)){
// Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
if(!(context instanceof SplashActivity)) {
if(!((Activity)context).isFinishing()){
showForceUpdateDialog();
}
}
}
}
super.onPostExecute(jsonObject);
}
public void showForceUpdateDialog(){
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
}
}
Firebase远程配置在这里可以提供最佳帮助,
除了使用JSoup之外,我们还可以进行模式匹配以从playStore获取应用程序版本。
为了匹配google play store即qazxsw poi的最新模式,我们首先要匹配上面的节点序列,然后从上面的序列中获取版本值。以下是相同的代码段:
<div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div>
我通过这个解决了这个问题。这也解决了Google在PlayStore中所做的最新更改。希望有所帮助。
使用将存储版本信息的服务器API
就像你说的那样。这是一种检测更新的简便方法。每次API调用都会传递您的版本信息。更新Playstore时更改服务器中的版本。一旦服务器版本高于已安装的应用程序版本,您就可以在API响应中返回状态代码/消息,可以处理并显示更新消息。如果你使用这种方法,你也可以阻止用户使用非常古老的应用程序,如WhatsApp。
或者你可以使用推送通知,这很容易做到...另外
此解决方案的完整源代码: private String getAppVersion(String patternString, String inputString) {
try{
//Create a pattern
Pattern pattern = Pattern.compile(patternString);
if (null == pattern) {
return null;
}
//Match the pattern string in provided string
Matcher matcher = pattern.matcher(inputString);
if (null != matcher && matcher.find()) {
return matcher.group(1);
}
}catch (PatternSyntaxException ex) {
ex.printStackTrace();
}
return null;
}
private String getPlayStoreAppVersion(String appUrlString) {
final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
String playStoreAppVersion = null;
BufferedReader inReader = null;
URLConnection uc = null;
StringBuilder urlData = new StringBuilder();
final URL url = new URL(appUrlString);
uc = url.openConnection();
if(uc == null) {
return null;
}
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
if (null != inReader) {
String str = "";
while ((str = inReader.readLine()) != null) {
urlData.append(str);
}
}
// Get the current version pattern sequence
String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
if(null == versionString){
return null;
}else{
// get version from "htlgb">X.X.X</span>
playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
}
return playStoreAppVersion;
}
https://stackoverflow.com/a/50479184/5740468
用法:
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class GooglePlayAppVersion extends AsyncTask<String, Void, String> {
private final String packageName;
private final Listener listener;
public interface Listener {
void result(String version);
}
public GooglePlayAppVersion(String packageName, Listener listener) {
this.packageName = packageName;
this.listener = listener;
}
@Override
protected String doInBackground(String... params) {
return getPlayStoreAppVersion(String.format("https://play.google.com/store/apps/details?id=%s", packageName));
}
@Override
protected void onPostExecute(String version) {
listener.result(version);
}
@Nullable
private static String getPlayStoreAppVersion(String appUrlString) {
String
currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>",
appVersion_PatternSeq = "htlgb\">([^<]*)</s";
try {
URLConnection connection = new URL(appUrlString).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
StringBuilder sourceCode = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sourceCode.append(line);
// Get the current version pattern sequence
String versionString = getAppVersion(currentVersion_PatternSeq, sourceCode.toString());
if (versionString == null) return null;
// get version from "htlgb">X.X.X</span>
return getAppVersion(appVersion_PatternSeq, versionString);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Nullable
private static String getAppVersion(String patternString, String input) {
try {
Pattern pattern = Pattern.compile(patternString);
if (pattern == null) return null;
Matcher matcher = pattern.matcher(input);
if (matcher.find()) return matcher.group(1);
} catch (PatternSyntaxException e) {
e.printStackTrace();
}
return null;
}
}
我会建议使用ex。推送通知以通知您的应用程序有新的更新,或使用您自己的服务器从那里启用您的应用程序读取版本。
是的,每次更新您的应用程序时,它的额外工作,但在这种情况下,您不依赖于某些可能用尽的“非官方”或第三方的事情。
万一你错过了什么 - 以前讨论你的主题new GooglePlayAppVersion(getPackageName(), version ->
Log.d("TAG", String.format("App version: %s", version)
).execute();