我正在尝试开发Android应用;我需要检查是否比现有的更高版本 - 从Play商店 - ?
我试着写这段代码:
try {
URL updateURL = new URL("https://play.google.com/store/apps/details?id=com.XXXX.YYYY");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
final String s = new String(baf.toByteArray());
/* Get current Version Number */
int curVersion = getPackageManager().getPackageInfo("com.XXXX.YYYY", 0).versionCode;
int newVersion = Integer.valueOf(s);
/* Is a higher version than the current already out? */
if (newVersion > curVersion) {
/* Post a Handler for the UI to pick up and open the Dialog */
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:com.XXXX.YYYY"));
startActivity(intent);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getStackTrace().toString(), Toast.LENGTH_LONG).show();
}
但此代码中的错误是:
java.net.UnknownHostException: Unable to resolve host "play.google.com": No address associated with hostname
Unable to resolve host "play.google.com": No address associated with hostname
答案 0 :(得分:1)
您的网络连接似乎存在问题。另外,请确保已在AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
上面显示的代码令人困惑。你怎么能以这种方式获得版本号?这个请求
URL updateURL = new URL("https://play.google.com/store/apps/details?id=com.XXXX.YYYY");
将在Google Play中返回您应用的HTML内容。如果没有进一步处理,您将无法获得该版本。
答案 1 :(得分:0)
doc.getElementsByAttributeValue
("itemprop", "softwareVersion").first().text();
softwareVersion不可用,请尝试以下代码
class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
Connection connection = Jsoup.connect(Config.APP_UPDATE_URL + "&hl=en");
Document document = connection.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();
Elements versions = document.getElementsByClass("htlgb");
for (int i = 0; i < versions.size(); i++) {
newVersion = versions.get(i).text();
if (Pattern.matches("^[0-9]{1}.[0-9]{1}.[0-9]{1}$", newVersion)) {
break;
}
}
} catch (Exception e) {
return newVersion;
}
return newVersion;
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (onlineVersion != null && !onlineVersion.isEmpty()) {
if (!onlineVersion.equalsIgnoreCase(currentVersionName)) {
startActivity(new Intent(SplashActivity.this, UpdateVersionActivity.class));
finish();
} else {
callPermission();
}
} else {
callPermission();
}
}
}