Google Play Licencing for an Android app in Android Studio - android

I am trying to set up Google Play Licencing for an app in Android studio for an app written in Kotlin. My goal is to avoid users sharing APK files without purchasing my app through the store.
What I've tried:
I've tried following through their documentation. It's not very useful. It skips over many details and it's not really a tutorial. I couldn't use it.
I've seen this question, which does have a long and detailed tutorial-like answer. But the answer seems long-outdated. It causes lots of warnings and terminates with an exception "Intent must be explicit".
My question in summary is:
How can I set up license checking through Google so people who haven't purchased the app through the store can't install it. This seems to be a very common thing to do even though I couldn't manage to find much of any proper answer around.

Here's how I got it working in 2020:
Open Android Studio.
Click Tools -> SDK Manager
Switch to the SDK Tools tab
Make sure Google Play Licensing Library is installed. If it's not installed, click the checkmark and click Apply.
Up in that screen you can see Android SDK Location. Copy that path:
Click File -> New -> Import Module...:
Paste the path you copied and click the small folder icon on the right of the text-input line:
Click Android\Sdk\extras\google\market_licensing\library and click OK:
Click Next:
Leave everything checked and click Finish:
Now you should have a library folder in your project:
Right click on app and click Open Module Settings:
Click Dependencies:
Click the plus button and choose 3 Module Dependency:
Check library and click OK:
Click OK again and wait for it to sync.
If you get an error
The minSdk version should not be declared in the android manifest file. You can move the version from the manifest to the defaultConfig in the build.gradle file.
Go to library > manifests > AndroidManifest.xml and remove the line <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="15" />.
Go to Gradle Scripts > build.gradle (Module: library):
Change minSdkVersion to 4 and also change compileSdkVersion, buildToolsVersion and targetSdkVersion as necessary, then click Sync Now:
Now that the library is ready, we need the actual implementation of the license checking. Go to MainActivity.kt.
You need to find your Base 64 public key and also generate a salt as shown in this answer. I am going to quote the necessary part of that answer but translate the code to Kotlin:
1.1 Your Base64 unique application key
How to get it:
a. Go to your developer console. Link.
b. If you haven't already created an application draft for your app, do it now.
c. Once you have created the draft, it is a good idea to upload your
.apk as Alpha or Beta. Leave it unpublished.
d. Click Services & APIs
e. Scroll down and find YOUR LICENSE KEY FOR THIS APPLICATION
f. Copy the key into your app like this:
private const val BASE64_PUBLIC_KEY = "YOUR LICENSE KEY FOR THIS APPLICATION";
Make sure that there are no spaces.
1.2 A salt
a. What is a salt?
A salt is random data that is additional input when hashing a
password. They are used to defend against dictionary attacks and
rainbow table attacks.
b. How do I get one?
This is a good link to generate a random salt. There should be exactly
20 random integers, so put 20 in for the amount of random strings to
generate, each string should be 2 characters long (used for this
example, it doesn't have to be). Check numeric digits, and check
Identical strings are allowed. They can be negative numbers too. Try
to remove any redundancy, e.g. 00 -> 0, for the sake of consistency.
c. Where do I put the salt?
When declaring variables just put this code in, except with your
random salt.
private val SALT = byteArrayOf(YOUR RANDOM SALT COMMA SEPARATED 20 INTEGERS)
Variables in step 21 should be added to your main activity class. Now, you should add some code to your main activity. Here's what it should roughly look like (Pay attention to // TODO comments):
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.vending.licensing.*
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity()
{
companion object
{
private const val BASE64_PUBLIC_KEY = "YOUR LICENSE KEY FOR THIS APPLICATION" // TODO replace with your own key
private val SALT = byteArrayOf(YOUR RANDOM SALT COMMA SEPARATED 20 INTEGERS) // TODO replace with your own salt
}
private val deviceId: String by lazy {
Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
}
private lateinit var licenseCheckerCallback: LicenseCheckerCallback
private lateinit var checker: LicenseChecker
private fun doCheck()
{
checker.checkAccess(licenseCheckerCallback)
}
override fun onDestroy()
{
super.onDestroy()
checker.onDestroy()
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
// Construct the LicenseCheckerCallback. The library calls this when done.
licenseCheckerCallback = MyLicenseCheckerCallback()
// Construct the LicenseChecker with a Policy.
checker = LicenseChecker(
this,
ServerManagedPolicy(this, AESObfuscator(SALT, packageName, deviceId)),
BASE64_PUBLIC_KEY // Your public licensing key.
)
doCheck()
setContentView(R.layout.activity_main) // TODO Replace with your own layout
}
private fun displayResult(result: String)
{
// TODO you can change this how the info is displayed
Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
}
private inner class MyLicenseCheckerCallback : LicenseCheckerCallback
{
override fun allow(reason: Int)
{
if (isFinishing)
{
// Don't update UI if Activity is finishing.
return
}
// Should allow user access.
}
override fun applicationError(errorCode: Int)
{
// TODO handle the error your own way. Calling `dontAllow` is common.
dontAllow(Policy.NOT_LICENSED)
}
override fun dontAllow(reason: Int)
{
if (isFinishing)
{
// Don't update UI if Activity is finishing.
return
}
if (reason == Policy.RETRY)
{
// If the reason received from the policy is RETRY, it was probably
// due to a loss of connection with the service, so we should give the
// user a chance to retry. So show a dialog to retry.
// TODO handle Policy.RETRY
}
else
{
// Otherwise, the user isn't licensed to use this app.
// Your response should always inform the user that the application
// isn't licensed, but your behavior at that point can vary. You might
// provide the user a limited access version of your app or you can
// take them to Google Play to purchase the app.
// TODO implement goto market
}
displayResult("Not Licensed")
// TODO you may not abort if you have some other way to handle the fail case
abort()
}
}
private fun abort()
{
finishAffinity()
exitProcess(0)
}
}
Add these permissions to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.android.vending.CHECK_LICENSE"/>
If you get an exception with a message similar to:
Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
Apply the fix in this answer.
That should be all. See the answer I quoted previously for more info. I hope this saves others some time.

Related

Android - Firebase Analytics doesnt log my event

I created a Roll dice app following the Google introduction course to Kotlin.
I am now implementing Firebase Analytics to track each dice rolled.
I followed Firebase instructions to install Firebase SDK within my gradle files.
I followed Google instruction to implement event tracking
I entered the 3 adb commands to see my log events in the Android Studio Logcat tab
But, I don´t know why my events aren't logged, they don't appear in my Logcat tab... When I initialize my app I can see various Firebase logs, but then when I click the button for which I have an event, Firebase doesn't log it. I checked my code and I don´t think problem comes from here.
Someone to help me?
I share with you my code and all messages I have in my terminal and catlog tabs.
package com.example.rolldiceapp
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.FirebaseAnalytics.Param.*
import com.google.firebase.analytics.ktx.logEvent
/*** This activity allows the user to roll a dice and view the result on the screen.***/
class MainActivity : AppCompatActivity() {
private lateinit var firebaseAnalytics: FirebaseAnalytics //Declare the FirebaseAnalytics object at the top of the activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) //Set layout with the Activity
firebaseAnalytics = FirebaseAnalytics.getInstance(this) //Initialize Firebase Analytics in the OnCreate method
val rollButton: Button = findViewById(R.id.roll_button)
rollButton.setOnClickListener {
rollDice()
trackClicks()
}
}
private fun rollDice() {
// Create new Dice object with 6 sides and roll it
val dice = Dice(6)
val diceRoll = dice.rollDice()
// Update the screen with the dice roll number
val resultTextView: TextView = findViewById(R.id.roll_textView)
resultTextView.text = diceRoll.toString()
// Update the screen with the dice roll image
val diceImage: ImageView = findViewById(R.id.roll_imageView)
diceImage.setImageResource(R.drawable.dice_2)
when (diceRoll) {
1 -> diceImage.setImageResource(R.drawable.dice_1)
2 -> diceImage.setImageResource(R.drawable.dice_2)
3 -> diceImage.setImageResource(R.drawable.dice_3)
4 -> diceImage.setImageResource(R.drawable.dice_4)
5 -> diceImage.setImageResource(R.drawable.dice_5)
6 -> diceImage.setImageResource(R.drawable.dice_6)
}
//Update the screen with result message
val luckyNumber = 4
val resultMessage: TextView = findViewById(R.id.resultRollText)
if (diceRoll == luckyNumber) {
resultMessage.text = ("You win! You rolled $diceRoll and it is the lucky number!").toString()
} else {
resultMessage.text = ("Sorry you rolled a $diceRoll and you need a $luckyNumber. Try again!").toString()
}
}
private fun trackClicks() {
firebaseAnalytics.logEvent("Click_Dice_track_2") {
param(SCREEN_NAME, "Dice_Homepage") // send predefined parameters
param(SCORE, value = "test")
param(SOURCE, "Local_Machine")
}
}
}
class Dice(val numSides: Int) {
fun rollDice(): Int {
return (1..numSides).random()
}
}
I share with you the messages I have in the Terminal and the Logcat tab when I initialize my application with Firebase.
You can try to Enabling debug mode
To enable Analytics Debug mode on an Android device, execute the following commands (do not forget to add package name) to terminal:
adb shell setprop debug.firebase.analytics.app com.example.rolldiceapp
If you have more than one emulator running, you have to use adb -s SERIAL (SERIAL for the unique id of the emulator). If one device and one emulator are connected you can use shortcuts: adb -d ... for device and adb -e ... for emulator.
After performing steps from Enabling debug mode, make sure that date and time on your debug device or emulator and on your PC is correct.
If after correcting the date and time events are still not showing on DebugView, clear the app storage. Then restart the app and try again.
Also make sure that you have the latest Google Play Services installed in the device/emulator or nothing is guaranteed to work.
If you go to the settings on your emulator, there is Update button for that. Unfortunately it requires you to sign-in via your Google account.
You can also study this question. Seems that your problem similar to this questions. So examine all answers, there are very useful

Kotlin-android: Unresolved reference

I have received this project from the previous developer, and he said everything is working fine on his end. But on my end, when I try to sync the project I get a lot of errors, and I don't know where to even start. One of them is this:
Here's that code:
private fun setupScrollDirection() {
val allowHorizontalScroll = config.scrollHorizontally && config.viewTypeFolders == VIEW_TYPE_GRID
excluded_vertical_fastscroller.isHorizontal = false
excluded_vertical_fastscroller.beGoneIf(allowHorizontalScroll)
excluded_vertical_fastscroller.allowBubbleDisplay = config.showInfoBubble
excluded_vertical_fastscroller.setViews(manage_folders_list) {
excluded_vertical_fastscroller.updateBubbleText(getBubbleTextItem(it))
}
}
I have a lot more errors of the same type, like this one for example:
Please have a call with the other developer and ask him/her to share his screen on call.
When the screen is being shared, ask the developer to Ctrl+ Click on beGoneIf variable/function and then check where the beGoneIf is defined in the project. This way you can check whether the required library/dependencies used by other developer is present in your local project or not.

Android dynamic feature module, resource not found

I'm having a problem starting an activity in a downloaded feature module when it's published to the play store. It always crashes on setContentView() in the downloaded modules activity.
java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx/xxxActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7e080000
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7e080000
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:227)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2149)
at android.content.res.Resources.getLayout(Resources.java:1158)
at android.view.LayoutInflater.inflate(LayoutInflater.java:421)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
The really strange part is that if I publish a new version of the app (only change is versionCode) to play store and update the app everything works perfectly.
When I uninstall the app and install it again the crash returns.
my Application is inheriting SplitCompatApplication() and just to be sure I've since tried to add:
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase)
SplitCompat.install(this)
}
to the activty in the feature module and disabled proguard to make sure nothing is removed during minify
My SplitInstallStateUpdatedListener
private val listener = SplitInstallStateUpdatedListener { state ->
val multiInstall = state.moduleNames().size > 1
state.moduleNames().forEach { name ->
// Handle changes in state.
when (state.status()) {
SplitInstallSessionStatus.DOWNLOADING -> {
// In order to see this, the application has to be uploaded to the Play Store.
displayLoadingState(state, "Laddar ner $name")
}
SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION -> {
/*
This may occur when attempting to download a sufficiently large module.
In order to see this, the application has to be uploaded to the Play Store.
Then features can be requested until the confirmation path is triggered.
*/
startIntentSender(state.resolutionIntent()?.intentSender, null, 0, 0, 0)
}
SplitInstallSessionStatus.INSTALLED -> {
if(toInstall.isNotEmpty() && toInstall.contains(name)) {
toInstall.remove(name)
}
if(toInstall.isEmpty()) {
// Updates the app’s context with the code and resources of the
// installed module. (should only be for instant apps but tried it anyway, no change)
SplitInstallHelper.updateAppInfo(applicationContext)
Handler().post {
viewModel.goToOverview()
}
}
}
SplitInstallSessionStatus.INSTALLING -> displayLoadingState(state, "Installerar $name")
SplitInstallSessionStatus.FAILED -> {
toastAndLog("Error: ${state.errorCode()} for module ${state.moduleNames()}")
}
}
}
}
This code downloads modules depending on user claims and starts an activity in the base app
The downloaded modules activity is then started from a BottomSheetDialogFragment like this:
xxx.setOnClickListener(view -> {
Intent intent = new Intent();
String packageName = Constants.MODULE_BASEPACKAGE + "." + Constants.MODULE_XXXXX;
intent.setClassName(getActivity().getPackageName(),packageName + ".XxxxxActivity" );
ParcelUuid parcelUuid = new ParcelUuid(UUID.randomUUID());
intent.putExtra("uuid", parcelUuid);
startActivity(intent);
dismiss();
});
I'm all out of ideas about what to try next. It seems like it's something that doesn't update the resource list until an update is installed and a restart of the app is not enough, or am I just missing something simple?
You can always access the resources from the main project inside the dynamic module, so you could just put your resources for the dynamic module in the main app, and then use the R.java from the main App.
However, the proper way to open these resources is to use SplitCompat.install(this) inside the dynamic delivered activity
This seems to have been a bug in com.android.tools.build:gradle:3.2.1
When I upgraded to 3.3.0 the problem resolved itself.
Hopefully it might help someone else who has this problem...
I had an exactly same problem; fresh install crashes with Resources$NotFoundException, but subsequent upgrade works OK (the dynamic module is not downloaded again). But my case was slightly different, because instead of starting an Activity in the dynamic module, I wanted to load a Fragment through Navigation. In that case, I should have just navigated and let Navigation do its thing without manually checking the module was loaded or not (refer to https://developer.android.com/guide/navigation/navigation-dynamic for more info).
// Just navigate without calling splitInstallManager.installedModules.contains()
findNavController().navigate(DynamicDeliveryDirections.actionDynamicFragment())
If you want to start an Activity, you do need to check whether the module is loaded or not, as you are already doing. I suggest you take a look at Google's example, which does exactly what you are trying to do.
https://codelabs.developers.google.com/codelabs/on-demand-dynamic-delivery/index.html?index=..%2F..index#1
As for my case, I had to make sure the package names were correct. For example, if the main module's package name is com.example.foo and dynamic module is com.example.foo.dynamic_activity, then starting the Activity in the dynamic module would look like the following.
Intent().setClassName(
"com.example.foo",
"com.example.foo.dynamic_activity.DynamicActivity"
).also {
startActivity(it)
}
I don't know why it works, but for me using AppCompatActivity solves this problem

Baidu maps on Android: access key does not work for location searching

I'm creating an Android app for a chinese client and they need map integration, so Google maps is not an option since all Google services are blocked in China. I'm trying to use Baidu maps, which is called Baidu LBS (location-based services) cloud.
Getting a basic map with no overlays to work was relatively easy. The process is described here (in Chinese, but the code speaks for itself if you don't understand the language). Downloading the latest Baidu Android SDK (v3.2.0 at time of writing) and integrating it into my Eclipse project as a library was no problem, but don't trust the documentation in that link too much even though it is the official one. Their examples often contain code that wouldn't even compile. The name of the .jar file for example was completely different from what you see in their screenshot.
Oh and also their .jar library is obfuscated which is super annoying to work with :-(
I needed to register a Baidu account and go to their control center to generate a key. To create an access key ("ak") for mobile you need to enter the SHA1 fingerprint of the keystore which signs your app, followed by the package name specified in your manifest.
Then I added the generated key to my manifest under the tag
<meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="xxx...xxx" />
I then copied code from their sample project's CloudSearchActivity because I have specific coordinates that I would like to display. I implemented the CloudListener interface as shown:
#Override
public void onGetSearchResult(final CloudSearchResult result, final int error)
{
Log.w("onGetSearchResult", "status=" + result.status + ". size=" + result.size + ". total=" + result.total + ". error=" + error);
if(null != result && null != result.poiList && 0 < result.poiList.size())
{
mBaiduMap.clear();
final BitmapDescriptor bitmapDescriptor=BitmapDescriptorFactory.fromResource(R.drawable.icon_address_grey);
LatLng latitudeLongitude;
LatLngBounds.Builder builder=new Builder();
for(final CloudPoiInfo info : result.poiList)
{
latitudeLongitude=new LatLng(info.latitude, info.longitude);
final OverlayOptions overlayOptions=new MarkerOptions().icon(bitmapDescriptor).position(latitudeLongitude);
mBaiduMap.addOverlay(overlayOptions);
builder.include(latitudeLongitude);
}
final LatLngBounds bounds=builder.build();
MapStatusUpdate mapStatusUpdate=MapStatusUpdateFactory.newLatLngBounds(bounds);
mBaiduMap.animateMapStatus(mapStatusUpdate);
}
}
And I added code to launch a query (also copied from their sample project):
#Override
public View onCreateView(final LayoutInflater layoutInflater, final ViewGroup viewGroup,
final Bundle savedInstanceState)
{
// initialize needs to be called
SDKInitializer.initialize(getApplication());
CloudManager.getInstance().init(MyFragment.this);
view=(ViewGroup)layoutInflater.inflate(R.layout.fragment_map, viewGroup, false);
mMapView=(MapView)view.findViewById(R.id.baiduMapView);
mBaiduMap=mMapView.getMap();
NearbySearchInfo info=new NearbySearchInfo();
info.ak="xxx...xxx";
info.geoTableId=12345;
info.tags="";
info.radius=30000;
info.location="116.403689,39.914957";
CloudManager.getInstance().nearbySearch(info);
return view;
}
Unfortunately I keep getting a status value of 102 from the server (according to this API page that means STATUS_CODE_SECURITY_CODE_ERROR. Now I don't know what to do.
Things that I don't understand:
Why do I need to repeat my access key ("ak") when building the query? Is it not enough to have it in the manifest once?
What is this "geoTableId" value in the query supposed to be?
Any ideas?
After many hours of research I have made some progress on the open questions.
The reason for the "ak" field in a cloud search query is not duplication, it is in fact a different access key. Somewhere in a hidden place Baidu says that access keys "for mobile" will not work for these cloud searches, you need an ak "for server". So the solution is to go back to the Baidu control center and create another key "for server". This key needs to be used in the query, while the "for mobile" key needs to remain in the manifest.
geoTableId is an identifier of your account, not unsimilar to the access keys. It is a (currently) 5 digit number that you need to obtain in the Baidu control center. The other keys were generated in the tab titled "API控制台" (API control desk), but for the geoTableId you need to switch to the tab called "数据管理" (data management). There I think I needed to press the "创建" (~create) button on top left, then enter a name, select "是" (yes) where they ask if this is for release (not sure about that translation) and then click "保存" (save). After this, your freshly generated number is displayed in the top field in parentheses behind the name you chose just now.
These steps have allowed me to send "successful" queries where the server answers with status 0 (STATUS_CODE_SUCCEED). However, so far all the answers I get are empty, I have yet to find a query which produces a non-empty answer. If anyone manages to do that, please let me know!

How to notify users about an Android app update?

I've built an Android app which is now on Play Market. From time to time, I make updates to it, and I'd like to let users know that a new version is available.
How can I send an update notification to the users of the app?
You do not need to do anything specific for this. Since you mentioned that you are using Google Play, the update notification is taken care of by Google Play.
You just need to update the APK with a higher versionCode and Google Play should do the rest.
Update 2020: now you can use in-app updates mechanism
Docs: https://developer.android.com/guide/playcore/in-app-updates
You can do this in a lot of ways, depending on when you want the user to be able to see that there is an update available.
If you want the user to know about the update when the app is started, just create a utility method (inside the onCreate method of your main/first Activity) that checks if a newer version is available in Google Play. If it does, display an alert dialog with a relevant message and an Intent which opens your app in Google Play when the user clicks on the positive button of the alert dialog.
If you are updating the app regularly, the user will keep getting this alert dialog every time the app is started and hence, may get irritated. Thus, this is not the best approach.
If you want the user to get a notification on the phone (and not when the user starts the app), you can use the AlarmManager class to schedule a background service which checks for an update at regular intervals. If the service finds that an upgrade is actually available, publish a notification with an intent that opens your app in Google Play.
Of course, another approach is to leave it to the OS itself. If the user has not set the "Automatically update" preference for your app, the user will get a notification regularly about an update available for your, as well as any other apps.
But not all users enable background data on their devices, so this is not completely reliable.
In the end, you must respect the users preferences. If the user does not want to automatically update the app, or does not want to see a nagging dialog box whenever he/she starts your app, don't alert the user about the update.
In my opinion, you should create a PreferenceActivity that has a preference like "Check for updates regularly", which can be set from within your app. If it is set, do the needful in your own service. May be even give the user an option to select the period after which the service will check for an update.
I hope this helps!
It is up to each phone owner if she wants to be notified on new versions by google play, and it's up to each phone's manufacturer if this is to be enabled by default.
If you however are in a situation where you "require" the user to update to the new version to be compatible with some form of protocol or you have a similar similar use case where you have a server component somewhere, you might want to notify the user of a potential version conflict in the UI based on information about what is the latest version.
This information can be grabbed directrly from google play, however as #Yahel pointed out in this question google play is a closed system with no official API, and you might need to rely on unpredictable undocumented API. There is an unofficial API library here.
This leaves only one option, which is to keep this information on your own server. If you allready have a serverside this might be trivial. Simply put the latest version in an XML file and retreive that at regular intervals from your code. If the version code is outdated, trigger the notification in your UI. Here is an example implementation for doing that.
I hope this was helpful :-)
I know this is an old question but still if people are coming here to check this question, Google is now providing official support for in-app notification for application update the full documentation can be found here
Use this : https://www.push-link.com/
Google Play will notify your users that the app has an update via the notification bar.
If you set up a notification system yourself, the likely result would be that, although the user is notified of an update sooner, when he/she goes to Google Play to install the update it will not yet be available. This is because there is a lag from the time you "publish" an app/update and the time until it appears on Play. Telling your users that there is an update when the update is unavailable would only lead to confusion and frustration.
My advice: stick with Google's update notification system and don't worry about trying to get users an update 15 minutes sooner.
Some people use Android Cloud-to-Device Messaging (C2DM) to notify their users of updates. I don't think I'd bother, since I think Google Play does a pretty good job of notifying me of updates already, and implementing C2DM adds a whole new dimension to writing an app (because it requires a server component). But maybe you want to offer your users a richer update notification than you get from Google Play.
#Davek804's answer above is wrong. android:versionCode is an integer value that represents the version of the application code, relative to other versions, so using "1.5b" there is incorrect. Use "15" (or "150") instead
Found a nice solution for your problem:
Let´s say you want to check for version updates manually on app start and notify your users for the new Update.
Step 1: Download android-market-api (not the .jar file, the full project!)
Step 2: After importing it to eclipse, write in your activity the following code:
MarketService ms = new MarketService(activity);
ms.level(MarketService.REVISION).checkVersion();
now, we need to modify MarketService.java, because it seems to be broken.
Step 3: rewrite callback method and add the following methods
protected void callback(String url, JSONObject jo, AjaxStatus status){
if(jo == null) return;
String googlePlayversion = jo.optString("version", "0");
String smartphone_version = "";
PackageInfo pInfo;
try {
pInfo = act.getPackageManager().getPackageInfo(act.getPackageName(), 0);
smartphone_version = pInfo.versionName;
} catch (NameNotFoundException e) {}
boolean new_version_avaible = compare(smartphone_version, googlePlayversion);
if(new_version_avaible){
showUpdateDialog(jo);
}
}
private static boolean compare(String v1, String v2) {
String s1 = normalisedVersion(v1);
String s2 = normalisedVersion(v2);
int cmp = s1.compareTo(s2);
String cmpStr = cmp < 0 ? "<" : cmp > 0 ? ">" : "==";
System.out.printf("result: "+"'%s' %s '%s'%n", v1, cmpStr, v2);
if(cmpStr.contains("<")){
return true;
}
if(cmpStr.contains(">")||cmpStr.contains("==")){
return false;
}
return false;
}
public static String normalisedVersion(String version) {
return normalisedVersion(version, ".", 4);
}
public static String normalisedVersion(String version, String sep, int maxWidth) {
String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
StringBuilder sb = new StringBuilder();
for (String s : split) {
sb.append(String.format("%" + maxWidth + 's', s));
}
return sb.toString();
}
If you want to test it, modify googlePlayversion string to a higher version than your local one.
The source comparison method I used is from How do you compare two version Strings in Java?
There is also a very good approach for checking version and give user in app notification or when you want to forcefully update the application if you can decide the first connection of your app with the server.In the response of the first request you can send the current version of app stored on your server and then on client end you can take the appropriate action.
Advantages of this approach-:
1-No extra request for version no.
2-It is also applicable if you are downloading the app other than the google playstore.
3-you can also use this idea if you want to check the version at particular operation of your app ex- transaction(if you add a new payment gateway.)
Don't know if you want to walk extra miles. You can try out google appengine, which serve version number for your app and let you android app check the appengine to see if there is a new version when the application is launched. That way, it does not matter if your app is in google play market nor amazon app store nor if it is installed on the phone without those two via sideloading. It is not very hard to setup appengine just for serving your application version in json. Replace "Hello World" string with your app version name ...
This can be using a simple webservice just this is one of the way to acheive.
i.e., when ever the app launch hit that webservice with the current version of the user app and on the server you need to check whether any new version is available or not(Must maintain the newest version of the app) and send the corresponding response to the user. If any newer version is available prompt the user to download the newest version of the application and if no newest version is available then allow the user to continue.
Hope so atleast something must be useful to you.
There are two models that are basically used to tackle the issue.
Pull Based
Push Based
Its depends on the architecture or design of particular system that determines whether pull based or push mechanism is used.
For pull based model you just make one http request to concerned server regarding the new version of application. The current application version no can be saved in SQLLite in android application. This can be given to server and new version can be checked against it at the server.
For push mechanism you can use C2DM push notification service.. details of which are given at http://code.google.com/android/c2dm/
Generally when you upload a new application to Google play most users get a notification about an update, some will have the app automatically downloaded to their device, depending on the settings they have.
If you seriously want to make a notification from your app to ask them to update (so that everyone gets the notification, whatever their Google play settings are, then you will have to make a web service which returns the number of the newest version. You can then compare that inside your app and post a notification. You could use Google App Engine ( https://developers.google.com/appengine/) because that works with eclipse and java, which you probably already have.
I would not recommend this approach as it creates a lot of work for you to provide something that most users have already got.
i think this is too late but it can be help some one
public enum AppVersionUpgradeNotifier {
INSTANCE;
private static final String TAG = "AppVersionUpdateManager";
private static final String PREFERENCES_APP_VERSION = "pref_app_version_upgrade";
private static final String KEY_LAST_VERSION = "last_version";
private SharedPreferences sharedPreferences;
private VersionUpdateListener versionUpdateListener;
private boolean isInitialized;
public static synchronized void init(Context context, VersionUpdateListener versionUpdateListener) {
if (context == null || versionUpdateListener == null) {
throw new IllegalArgumentException(TAG + " : Context or VersionUpdateListener is null");
}
if (!INSTANCE.isInitialized) {
INSTANCE.initInternal(context, versionUpdateListener);
} else {
Log.w(TAG, "Init called twice, ignoring...");
}
}
private void initInternal(Context context, VersionUpdateListener versionUpdateListener) {
this.sharedPreferences = context.getSharedPreferences(PREFERENCES_APP_VERSION, Context.MODE_PRIVATE);
this.versionUpdateListener = versionUpdateListener;
this.isInitialized = true;
checkVersionUpdate();
}
private void checkVersionUpdate() {
int lastVersion = getLastVersion();
int currentVersion = getCurrentVersion();
if (lastVersion < currentVersion) {
if (versionUpdateListener.onVersionUpdate(currentVersion, lastVersion)) {
upgradeLastVersionToCurrent();
}
}
}
private int getLastVersion() {
return sharedPreferences.getInt(KEY_LAST_VERSION, 0);
}
private int getCurrentVersion() {
return BuildConfig.VERSION_CODE;
}
public void upgradeLastVersionToCurrent() {
sharedPreferences.edit().putInt(KEY_LAST_VERSION, getCurrentVersion()).apply();
}
public interface VersionUpdateListener {
boolean onVersionUpdate(int newVersion, int oldVersion);
}
}
use it on
public class MyApplication extends Application implements AppVersionUpgradeNotifier.VersionUpdateListener {
#Override
public void onCreate() {
super.onCreate();
AppVersionUpgradeNotifier.init(this,this);
}
#Override
public boolean onVersionUpdate(int newVersion, int oldVersion) {
//do what you want
return true;
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1.5b"
android:versionName="1.5b">
When you re-upload your app to Google Play, if these two attributes have been changed from the previous upload, Google Play will automatically send notifications to users who have installed your app. This is the AndroidManifest file.

Categories

Resources