Looking up version and forcing an update in xamarin - android

There are many posts about doing this in java, but I found that NSoup (the port of the JSoup library) doesn't work for me, so I failed to port it to c#/Xamarin. For multiplayer functions of a game I'm working on, I need to make sure clients are synced before starting multiplayer matchmaking. This means I have to force the user to update the app if there's a new version available before they're allowed to invite other players to matches, join quick matches, etc..
So when a user presses the "quick match" button, for example, I need to:
Check for the version name (im incrementing version name, not code, for breaking changes)
Compare the version name from that to the current version name installed
3.
-If the newer version name is greater than the current one, I need to give the user the option to update their app, and send them to the google play store page for my app if they choose 'yes'. Then I'll just let them update from there and our work is done.
-If the versions are the same, allow whatever the button's functionality (i.e sending them to the waiting room for matchmaking) to proceed.

Create the methods necessary to check for updates and act accordingly:
private void CheckUpdate(Action doIfUpToDate)
{
if(NeedUpdate())
{
Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
alert.SetTitle("New Update");
alert.SetMessage("You must download the newest version of this to play multiplayer. Would you like to now?");
alert.SetCancelable(false);
alert.SetPositiveButton("Yes", new EventHandler<DialogClickEventArgs>((object sender, DialogClickEventArgs e) => GetUpdate()));
alert.SetNegativeButton("No", delegate{});
alert.Show();
}
else
{
doIfUpToDate.Invoke();
}
}
private bool NeedUpdate()
{
try
{
var curVersion = PackageManager.GetPackageInfo(PackageName, 0).VersionName;
var newVersion = curVersion;
string htmlCode;
//probably better to do in a background thread
using (WebClient client = new WebClient())
{
htmlCode = client.DownloadString("https://play.google.com/store/apps/details?id=" + PackageName + "&hl=en");
}
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlCode);
newVersion = doc.DocumentNode.SelectNodes("//div[#itemprop='softwareVersion']")
.Select(p => p.InnerText)
.ToList()
.First()
.Trim();
return String.Compare(curVersion, newVersion) < 0;
}
catch (Exception e)
{
Log.Error(TAG, e.Message);
Toast.MakeText(this, "Trouble validating app version for multiplayer gameplay.. Check your internet connection", ToastLength.Long).Show();
return true;
}
}
private void GetUpdate()
{
try
{
StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse("market://details?id=" + PackageName)));
}
catch (ActivityNotFoundException e)
{
//Default to the the actual web page in case google play store app is not installed
StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse("https://play.google.com/store/apps/details?id=" + PackageName)));
}
}
And then from a given button that could start a multiplayer game:
var quickMatchButton = FindViewById<Button>(Resource.Id.button_quick_game);
quickMatchButton.Click += new EventHandler((object sender, EventArgs e) => CheckUpdate(() => startQuickMatch()));

Related

IBM Watson UnAuthorized

I implemented IBM watson Assistant and it works perfectly fine on android debug. Problem comes when I build a signed apk. It always says Unauthorized. I don't think its the key because its working fine on debug mode. I need some help because the project is live.
What I have tried so far is to change the key in IBM cloud and tried other keys but it raises not found exception of which i think is caused by wrong key. Im I supposed to allow something in IBM cloud for signed apk? or is there a certificate from signed apk that I have to upload in IBM cloud?
Im using IBM watson Assistant v2
private Assistant watsonAssistant;
private Response<SessionResponse> watsonAssistantSession;
private void createServices() {
watsonAssistant = new Assistant("2020-04-01", new IamAuthenticator(getString(R.string.assistant_apikey)));
watsonAssistant.setServiceUrl(getString(R.string.assistant_url));
}
private void sendMessage(){
Thread thread = new Thread(() -> {
try {
if (watsonAssistantSession == null) {
ServiceCall<SessionResponse> call = watsonAssistant.createSession(new CreateSessionOptions.Builder().assistantId(getString(R.string.normal_assistant_id)).build());
watsonAssistantSession = call.execute();
}
MessageInput input = new MessageInput.Builder()
.text(userInput)
.build();
MessageOptions options = new MessageOptions.Builder()
.assistantId(getString(R.string.normal_assistant_id))
.input(input)
.sessionId(watsonAssistantSession.getResult().getSessionId())
.build();
Response<MessageResponse> response = watsonAssistant.message(options).execute();
if (response.getResult().getOutput() != null && !response.getResult().getOutput().getGeneric().isEmpty()) {
List<RuntimeResponseGeneric> responses = response.getResult().getOutput().getGeneric();
for (RuntimeResponseGeneric r : responses) {
switch (r.responseType()) {
case "text":
aiResponse = r.text();
aiConversationList.add(new AIConversation(r.text(), "ai", System.currentTimeMillis()));
break;
default:
Log.e("Error", "Unhandled message type");
}
}
runOnUiThread(() -> {
sendConvoToServer(userInput, aiResponse);
txtWelcomeAI.setVisibility(View.VISIBLE);
aiAdapter.notifyItemInserted(aiConversationList.size() - 1);
userInputTxt.setEnabled(true);
pRecyclerView.scrollToPosition(aiConversationList.size() - 1);
aStatus.setText("online");
});
}
} catch (Exception e) {
e.printStackTrace();
Log.e("IBM_EXCEPTION", e.toString());
aiConversationList.add(new AIConversation("Oops! Something went wrong", "ai", System.currentTimeMillis()));
aiAdapter.notifyItemInserted(aiConversationList.size() - 1);
runOnUiThread(() -> {
pRecyclerView.scrollToPosition(aiConversationList.size() - 1);
aStatus.setText("online");
userInputTxt.setEnabled(true);
});
}
});
thread.start();
}
In case anyone else will have a problem between debug and release apks like the one I had, try to check if you have done obfuscation. If so, then obfuscation is probably a problem. At least it was for me. So, either disable obfuscation from your build.gradle on app level or add some rules in proguard-rules

Android: Receiving wrong UTM from Google Ads

According to my boss, some of our applications have been invested on advertising of the app via Google Ads. In order for them to parse the data and analyze them correctly, they are using the UTM auto-tagging approach. It is my job from the client (Android Device) to send the UTM using Firebase Analytics and also a custom event to Firebase depending on this UTM.
However, our data shows that both Firebase SDK and our events are transferred incorrectly. The click numbers and the download numbers do not match. Since both of them are incorrect, I'm guessing the received UTM on the device itself is wrong, and this needs to be received correctly and I am unable to find an answer for this.
I'm using Install Referrer Library to track down what the UTM is after the app is downloaded to the device. I am guessing Firebase SDK also uses somewhat similar approach. On our end, the UTM is recorded to SharedPreferences and it is not queried again if the query was successful.
Here is the related code for it (the processReferrer method basically parses the UTM according to our needs):
/**
* Checks if the referrer information is recorded before, if not, creates
* a connection to Google Play and saves the data to shared preferences.
*/
private static void fetchReferrerInformation(Context context)
{
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
String utmData = preferences.getString(UTM_DATA, "");
// Only connect if utm is not recorded before.
if (TextUtils.isEmpty(utmData))
{
InstallReferrerClient client;
try
{
client = InstallReferrerClient.newBuilder(context).build();
client.startConnection(new InstallReferrerStateListener()
{
#Override
public void onInstallReferrerSetupFinished(int responseCode)
{
switch (responseCode)
{
case InstallReferrerClient.InstallReferrerResponse.OK:
{
ReferrerDetails response;
try
{
response = client.getInstallReferrer();
}
catch (Exception e)
{
Log.e(TAG, "Error while fetching referrer information.", e);
if (Fabric.isInitialized())
Crashlytics.logException(new IllegalStateException("Exception while fetching UTM information.", e));
return;
}
if (response != null)
{
processReferrer(context, response.getInstallReferrer());
}
break;
}
case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
{
Log.w(TAG, "Install referrer client: Feature is not supported.");
break;
}
case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE:
{
Log.w(TAG, "Install referrer client: Service is unavailable.");
break;
}
}
try
{
client.endConnection();
}
catch (Exception ignored){}
}
#Override
public void onInstallReferrerServiceDisconnected()
{
// Do nothing, we need to fetch the information once and
// it is not really necessary to try to reconnect.
// If app is opened once more, the attempt will be made anyway.
}
});
}
catch (Exception e)
{
if (Fabric.isInitialized())
Crashlytics.logException(new IllegalStateException("Exception while fetching UTM information.", e));
}
}
else
Log.i(TAG, "UTM is already recorded, skipping connection initialization. Value: " +
utmData);
}
The approach is pretty simple, however the data seems to be wrong. So, does it seem that the implementation is somewhat incorrect? If not, why is the data received from Google Ads is wrong? Any help is appreciated, thank you very much.
Edit: Upon some testing, here is what I've found:
Works:
An API 19 real device (GM Discovery II Mini) and in between API 25-29 emulators with Play Store installed. Edit: UTM can also be fetched with API 23 and 24 Genymotion Emulators, where Play Store is installed.
Doesn't work:
An API 24 Android Studio emulator with latest Google Play Services and Play Store installed (device is also logged in to my account), and a real device (General Mobile 4G Dual, API 23) cannot query the UTM information. The code below lands on the case of InstallReferrerResponse.FEATURE_NOT_SUPPORTED. So I am almost sure that the install referrer client is bugged on some API levels.
Edit: Opened an issue to the Google: https://issuetracker.google.com/issues/149342702
As I don't know how you are processing the resonse, I can show you the way we did it in our implementation.
ReferrerDetails response = referrerClient.getInstallReferrer();
if (response == null) {
break;
}
String[] installReferrer = response.getInstallReferrer().split("&");
if (installReferrer.length >= 1) {
utmSource = installReferrer[0].split("=")[1];
}
if (installReferrer.length >= 2) {
utmMedium = installReferrer[1].split("=")[1];
}
Compare this snippet with yours and check if anything differs.

Is Google play caching the products purchased for offline reference?

Confused as to how the billing service is validating an old purchase after uninstall / reinstall, clearing app data and while the device is offline. I am using James Montemagno's Plugin.InAppBilling for Xamarin. I have a pretty simple MyProduct kind of class with this function.
The IEnumerable that is returned from GetPurchasesAsync has my test purchase in it, when the device is offline. Is this information stored in google play services offline? How do I get rid of it?
public async Task<bool> WasItemPurchased()
{
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync();
if (!connected)
{
//Couldn't connect
this.PurchYN = false;
}
//check purchases
var purchases = await billing.GetPurchasesAsync(ItemType.InAppPurchase);
//check for null just incase
if (purchases?.Any(p => p.ProductId == this.AppProdID) ?? false)
{
//Purchase restored
this.PurchYN = true;
}
else
{
//no purchases found
this.PurchYN = false;
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
//Billing Exception handle this based on the type
Debug.WriteLine("Error: " + purchaseEx);
}
catch (Exception ex)
{
this.PurchYN = false;
}
finally
{
await billing.DisconnectAsync();
}
return this.PurchYN;
}
If you clear the cached data for the Play store it should get rid of it.

Programmatically check Play Store for app updates

I have put my app on the Google Play Store. It has been installed by lots of my company's customers. I understand the mechanism of how the app is intended to upgrade.
The users should check the auto-update check box in the Playstore app for each app they want to auto-update. However some users have unchecked it or not checked it in the first place.
The app i have written is for the care industry and is used by carers to deliver homecare. Some of our customers my have 1200 carers. They would have to call all the carers into the office to update the phones individually. This is obviously unacceptable.
Is there a way to programmatically check if there is an updated version of my app on the Play Store?
Could i have code that runs every time the user starts the app that checks the Play Store?
If there is an updated version then the user could be directed to the Playstore. This will mean it is not essential to have the auto-update checked.
Update 17 October 2019
https://developer.android.com/guide/app-bundle/in-app-updates
Update 24 april 2019:
Android announced a feature which will probably fix this problem. Using the in-app Updates API:
https://android-developers.googleblog.com/2018/11/unfolding-right-now-at-androiddevsummit.html
Original:
As far a I know, there is no official Google API which supports this.
You should consider to get a version number from an API.
Instead of connecting to external APIs or webpages (like Google Play Store).
There is a risk that something may change in the API or the webpage, so you should consider to check if the version code of the current app is below the version number you get from your own API.
Just remember if you update your app, you need to change the version in your own API with the app version number.
I would recommend that you make a file in your own website or API, with the version number. (Eventually make a cronjob and make the version update automatic, and send a notification when something goes wrong)
You have to get this value from your Google Play Store page (is changed in the meantime, not working anymore):
<div class="content" itemprop="softwareVersion"> x.x.x </div>
Check in your app if the version used on the mobile is below the version nummer showed on your own API.
Show indication that she/he needs to update with a notification, ideally.
Things you can do
Version number using your own API
Pros:
No need to load the whole code of the Google Play Store (saves on data/bandwidth)
Cons:
User can be offline, which makes checking useless since the API can't be accessed
Version number on webpage Google Play Store
Pros:
You don't need an API
Cons:
User can be offline, which makes checking useless since the API can't be accessed
Using this method may cost your users more bandwidth/mobile data
Play store webpage could change which makes your version 'ripper' not work anymore.
Include JSoup in your apps build.gradle file :
dependencies {
compile 'org.jsoup:jsoup:1.8.3'
}
and get current version like :
currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
And execute following thread :
private class GetVersionCode extends AsyncTask<Void, String, String> {
#Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.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(".hAyfc .htlgb")
.get(7)
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
#Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
if (onlineVersion != null && !onlineVersion.isEmpty()) {
if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
//show dialog
}
}
}
For more details visit : http://revisitingandroid.blogspot.in/2016/12/programmatically-check-play-store-for.html
Firebase Remote Config could be a possible and reliable solution for now, since google didn't expose any api to it.
Check Firebase Remote Config Docs
Steps
1.Create a firebase project and add google_play_service.json to your project
2.Create keys like "android_latest_version_code" and "android_latest_version_name" in firebase console->Remote Config
3.Android Code
public void initializeFirebase() {
if (FirebaseApp.getApps(mContext).isEmpty()) {
FirebaseApp.initializeApp(mContext, FirebaseOptions.fromResource(mContext));
}
final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
config.setConfigSettings(configSettings);
}
Get current version name and code
int playStoreVersionCode = FirebaseRemoteConfig.getInstance().getString(
"android_latest_version_code");
PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
int currentAppVersionCode = pInfo.versionCode;
if(playStoreVersionCode>currentAppVersionCode){
//Show update popup or whatever best for you
}
4. And keep firebase "android_latest_version_code" and "android_latest_version_name" upto date with your current production version name and code.
Firebase remote config works on both Android and IPhone.
You can get current Playstore Version using JSoup with some modification like below:
#Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.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(".hAyfc .htlgb")
.get(7)
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
#Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
Log.d("update", "playstore version " + onlineVersion);
}
answer of #Tarun is not working anymore.
Google has introduced in-app updates API
The API currently supports two flows:
The “immediate” flow is a full-screen user experience that guides the user from download to update before they can use your app.
The “flexible flow” allows users to download the update while continuing to use your app.
There's AppUpdater library.
How to include:
Add the repository to your project build.gradle:
allprojects {
repositories {
jcenter()
maven {
url "https://jitpack.io"
}
}
}
Add the library to your module build.gradle:
dependencies {
compile 'com.github.javiersantos:AppUpdater:2.6.4'
}
Add INTERNET and ACCESS_NETWORK_STATE permissions to your app's Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Add this to your activity:
AppUpdater appUpdater = new AppUpdater(this);
appUpdater.start();
#Tarun answer was working perfectly.but now isnt ,due to the recent changes from Google on google play website.
Just change these from #Tarun answer..
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);
}
}
and don't forget to add JSoup library
dependencies {
compile 'org.jsoup:jsoup:1.8.3'}
and on 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();
}
that's it..
Thanks to this link
Coming From a Hybrid Application POV.
This is a javascript example, I have a Update Available footer on my main menu. If an update is available (ie. my version number within the config file is less than the version retrieved, display the footer) This will then direct the user to the app/play store, where the user can then click the update button.
I also get the whats new data (ie Release Notes) and display these in a modal on login if its the first time on this version.
On device Ready, set your store URL
if (device.platform == 'iOS')
storeURL = 'https://itunes.apple.com/lookup?bundleId=BUNDLEID';
else
storeURL = 'https://play.google.com/store/apps/details?id=BUNDLEID';
The Update Available method can be ran as often as you like. Mine is ran every time the user navigates to the home screen.
function isUpdateAvailable() {
if (device.platform == 'iOS') {
$.ajax(storeURL, {
type: "GET",
cache: false,
dataType: 'json'
}).done(function (data) {
isUpdateAvailable_iOS(data.results[0]);
}).fail(function (jqXHR, textStatus, errorThrown) {
commsErrorHandler(jqXHR, textStatus, false);
});
} else {
$.ajax(storeURL, {
type: "GET",
cache: false
}).done(function (data) {
isUpdateAvailable_Android(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
commsErrorHandler(jqXHR, textStatus, false);
});
}
}
iOS Callback: Apple have an API, so very easy to get
function isUpdateAvailable_iOS (data) {
var storeVersion = data.version;
var releaseNotes = data.releaseNotes;
// Check store Version Against My App Version ('1.14.3' -> 1143)
var _storeV = parseInt(storeVersion.replace(/\./g, ''));
var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
$('#ft-main-menu-btn').off();
if (_storeV > _appV) {
// Update Available
$('#ft-main-menu-btn').text('Update Available');
$('#ft-main-menu-btn').click(function () {
openStore();
});
} else {
$('#ft-main-menu-btn').html(' ');
// Release Notes
settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
}
}
Android Callback: PlayStore you have to scrape, as you can see the version is relatively easy to grab and the whats new i take the html instead of the text as this way I can use their formatting (ie new lines etc)
function isUpdateAvailable_Android(data) {
var html = $(data);
var storeVersion = html.find('div[itemprop=softwareVersion]').text().trim();
var releaseNotes = html.find('.whatsnew')[0].innerHTML;
// Check store Version Against My App Version ('1.14.3' -> 1143)
var _storeV = parseInt(storeVersion.replace(/\./g, ''));
var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
$('#ft-main-menu-btn').off();
if (_storeV > _appV) {
// Update Available
$('#ft-main-menu-btn').text('Update Available');
$('#ft-main-menu-btn').click(function () {
openStore();
});
} else {
$('#ft-main-menu-btn').html(' ');
// Release Notes
settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
}
}
The open store logic is straight forward, but for completeness
function openStore() {
var url = 'https://itunes.apple.com/us/app/appname/idUniqueID';
if (device.platform != 'iOS')
url = 'https://play.google.com/store/apps/details?id=appid'
window.open(url, '_system')
}
Ensure Play Store and App Store have been Whitelisted:
<access origin="https://itunes.apple.com"/>
<access origin="https://play.google.com"/>
Firebase Remote Config is better.
Quickly and easily update our applications without the need to publish a new build to the app
Implementing Remote Config on Android
Adding the Remote Config dependancy
compile 'com.google.firebase:firebase-config:9.6.0'
Once done, we can then access the FirebaseRemoteConfig instance throughout our application where required:
FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
Retrieving Remote Config values
boolean someBoolean = firebaseRemoteConfig.getBoolean("some_boolean");
byte[] someArray = firebaseRemoteConfig.getByteArray("some_array");
double someDouble = firebaseRemoteConfig.getDouble("some_double");
long someLong = firebaseRemoteConfig.getLong("some_long");
String appVersion = firebaseRemoteConfig.getString("appVersion");
Fetch Server-Side values
firebaseRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFirebaseRemoteConfig.activateFetched();
// We got our config, let's do something with it!
if(appVersion < CurrentVersion){
//show update dialog
}
} else {
// Looks like there was a problem getting the config...
}
}
});
Now once uploaded the new version to playstore, we have to update the version number inside firebase. Now if it is new version the update dialog will display
Inside OnCreate method write below code..
VersionChecker versionChecker = new VersionChecker();
try {
latestVersion = versionChecker.execute().get();
Toast.makeText(getBaseContext(), latestVersion , Toast.LENGTH_SHORT).show();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
this gives you play store version of app..
then you have to check app version as below
PackageManager manager = getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
assert info != null;
version = info.versionName;
after that you can compare it with store version and setup your own update screens
if(version.equals(latestVersion)){
Toast.makeText(getBaseContext(), "No Update" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getBaseContext(), "Update" , Toast.LENGTH_SHORT).show();
}
And add VersionChecker.class as below
public class VersionChecker extends AsyncTask<String, String, String> {
private 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(".hAyfc .htlgb")
.get(7)
.ownText();
} catch (IOException e) {
e.printStackTrace();
}
return newVersion;
}
}
Set up a server that exposes an HTTP url that reports the latest version, then use an AlarmManager to call that URL and see if the version on the device is the same as the latest version. If it isn't pop up a message or notification and send them to the market to upgrade.
There are some code examples: How to allow users to check for the latest app version from inside the app?
Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.
To match the latest pattern from google playstore ie
<div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div>
we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:
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;
}
I got it solved through this, as this works for latest Google playstore changes also. Hope that helps.
private void CheckUPdate() {
VersionChecker versionChecker = new VersionChecker();
try
{ String appVersionName = BuildConfig.VERSION_NAME;
String mLatestVersionName = versionChecker.execute().get();
if(!appVersionName.equals(mLatestVersionName)){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
alertDialog.setTitle("Please update your app");
alertDialog.setMessage("This app version is no longer supported. Please update your app from the Play Store.");
alertDialog.setPositiveButton("UPDATE NOW", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String appPackageName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
alertDialog.show();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
#SuppressLint("StaticFieldLeak")
public class VersionChecker extends AsyncTask<String, String, String> {
private String newVersion;
#Override
protected String doInBackground(String... params) {
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+getPackageName())
.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();
} catch (IOException e) {
e.printStackTrace();
}
return newVersion;
}
}
There is no official GooglePlay API to do it.
But you can use this unofficial library to get app version data.
And, if the above doesn't work for you, you can always http connect to your app's page (e.g. https://play.google.com/store/apps/details?id=com.shots.android&hl=en) and parse the "Current Version" field.
You can try following code using Jsoup
String latestVersion = doc.getElementsContainingOwnText("Current Version").parents().first().getAllElements().last().text();
Google introduced In-app updates feature, (https://developer.android.com/guide/app-bundle/in-app-updates) it works on Lollipop+ and gives you the ability to ask the user for an update with a nice dialog (FLEXIBLE) or with mandatory full-screen message (IMMEDIATE).
Here is how Flexible update will look like:
and here is Immedtiate update flow:
You can check my answer here https://stackoverflow.com/a/56808529/5502121 to get the complete sample code of implementing both Flexible and Immediate update flows.
Hope it helps!
confirmed only that method work now:
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + AcMainPage.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(".hAyfc .htlgb")
.get(5)
.ownText();
Google introduced in-app update api. Using that we can ask user to update app inside the application. if user accept we can directly download latest app and install without redirect to playstore. for more details please refer the below link
link1link2
I am not sure about JAVA programming though, but with latest changes you can
Request https://play.google.com/store/apps/details?id=<package.name> url.
Parse the data as text.
Match regex /key: 'ds:4',\n[\ ]*hash: '[0-9]*',\n[\ ]*data:\ ([\S".,\[\]\ ]*),/ with the response.
This has a group with it which will give group value as ["size", "version", "supported android version"]. e.g. ["16M", "1.0.0", "5.0 and up"].
Parse the group as an array and you will get array[1] as latest version.
Implementation doesn't depend on any language.
if your app is on Google Play Store then Just use this function its automatically checks the app update and shows a msg to the user for update
public void checkUpdate()
{
if (isInternetOn())
{
AppUpdateManager appUpdateManager = AppUpdateManagerFactory.create(getApplicationContext());
Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE))
{
try {
appUpdateManager.startUpdateFlowForResult(appUpdateInfo, AppUpdateType.FLEXIBLE, this, "Your Request Code");
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});
}
}
and additionally you can check internet Connectivity before checking the update with this function`
public boolean isInternetOn()
{
ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED)
{
return true;
} else if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED)
{
return false;
}
return false;
}`

Setting Account sync indicator red (or other colors too)

I'm trying to indicate the authentication / sync status of an account using the AccountAuthenticator and SyncAdapter. I've been through the samples, and can get it working alright.
How can I set the indicator to red just like the GMail account?
I'd also like to add additional status indicators on the sync adapter page. See picture below:
Answering my own question for future team knowledge...
Getting the indicator to change color was fairly easy after some experimentation. Start by creating a project based on thecode supplied in the SDK sample projects, modify as follows:
1) Fake the initial login from the server during the AuthenticationActivity. Once past the initial check, the system will start it's periodic sync attempts.
/**
* Called when the authentication process completes (see attemptLogin()).
*/
public void onAuthenticationResult(boolean result) {
Log.i(TAG, "onAuthenticationResult(" + result + ")");
// Hide the progress dialog
hideProgress();
// Override the result, we don't care right now....
result = true;
if (result) {
if (!mConfirmCredentials) {
finishLogin();
} else {
finishConfirmCredentials(true);
}
} else {
Log.e(TAG, "onAuthenticationResult: failed to authenticate");
if (mRequestNewAccount) {
// "Please enter a valid username/password.
mMessage.setText(getText(R.string.login_activity_loginfail_text_both));
} else {
// "Please enter a valid password." (Used when the
// account is already in the database but the password
// doesn't work.)
mMessage.setText(getText(R.string.login_activity_loginfail_text_pwonly));
}
}
}
2) Modify the "onPerformSync()" method within the SyncAdapter. The key here are the "syncResult.stats" fields. While modifying them, I found that inserting multiple errors didn't get the effect I wanted. Also noting that the counts didn't seem to be recorded across sync attempts (i.e. the fails always come in as zero). The "lifetimeSyncs" is a static variable that keeps count across sync attempts. This modified code will continue to alternate between green and red...
#Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
List<User> users;
List<Status> statuses;
String authtoken = null;
try {
// use the account manager to request the credentials
authtoken = mAccountManager.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true );
// fetch updates from the sample service over the cloud
//users = NetworkUtilities.fetchFriendUpdates(account, authtoken, mLastUpdated);
// update the last synced date.
mLastUpdated = new Date();
// update platform contacts.
Log.d(TAG, "Calling contactManager's sync contacts");
//ContactManager.syncContacts(mContext, account.name, users);
// fetch and update status messages for all the synced users.
//statuses = NetworkUtilities.fetchFriendStatuses(account, authtoken);
//ContactManager.insertStatuses(mContext, account.name, statuses);
if (SyncAdapter.lifetimeSyncs-- <= 0 ){
//mAccountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authtoken);
syncResult.stats.numAuthExceptions++;
//syncResult.delayUntil = 60;
lifetimeSyncs = 5;
}
} catch (final AuthenticatorException e) {
syncResult.stats.numParseExceptions++;
Log.e(TAG, "AuthenticatorException", e);
} catch (final OperationCanceledException e) {
Log.e(TAG, "OperationCanceledExcetpion", e);
} catch (final IOException e) {
Log.e(TAG, "IOException", e);
Log.d(TAG, extras.toString());
syncResult.stats.numAuthExceptions++;
syncResult.delayUntil = 60;
//extras.putString(AccountManager.KEY_AUTH_FAILED_MESSAGE, "You're not registered");
} catch (final ParseException e) {
syncResult.stats.numParseExceptions++;
Log.e(TAG, "ParseException", e);
}
}
That's it, enjoy playing with the delays and other variables too...

Categories

Resources