NativeScript Monetization and Ads, AdMob plugin - google-play

I want to create a paid app with nativescript and keep it in "play store". But I want to allow to download my app as "free with ads" in it. Which option should I use? If I choose the paid version then it is not available to download so should I choose "pay in app" ?
https://play.google.com/about/monetization-ads/payments/
I intend to use NativeScript AdMob plugin to manage ads but how can I know that user has paid already and I should to not init my ads for him?
https://plugins.nativescript.rocks/plugin/nativescript-admob

Let's assume you are using nativescript-admob plugin alongside nativescript-purchase. Then you could track when a product is purchased or restored and "remember" this via the application-settings module.
For example,
import {getBoolean, setBoolean } from "tns-core-modules/application-settings";
// ... more code follow here
if (transaction.transactionState === TransactionState.Purchased) {
/* Purchase of the FULL version */
if (transaction.productIdentifier.indexOf(".full") >= 0) {
setBoolean(transaction.productIdentifier, true);
}
// ... more code follows here
Then, before opening an AdMob advertisement, check if the product is puchased via the getBoolean.
For example:
this.isPurchased = getBoolean(fullVersionPurchase); // fullVersionPurchase === transaction.productIdentifie
if (!this.isPurchased) {
this.showBanner(); // where showBaneer is your AdMob functionality
}
And following the same logic, you could directly close the banner immediately after a successful purchase (or restore).
if (transaction.transactionState === TransactionState.Purchased) {
if (transaction.productIdentifier.indexOf(".full") >= 0) {
setBoolean(transaction.productIdentifier, true);
}
try {
admob.hideBanner();
} catch (err) { }
With the above approach, you could create a free app that comes with AdMob and then when a user purchases the full version to immediately provide the full version functionalities. See here for more details on the nativescript-purchase functionalities.

Related

How to automatically update the UI after user updates a userProperty in Google Apps Script Workspace Add-ons for Google Sheets?

I want to automagically update the UI with a new user setting after the user updates that setting by submitting a user input from.
Currently, I am attempting to use the updateCard() method from the CardService as shown in the below code. The docs are here but they do not contain any example code.
I expect that after the user provides the input and submits it, the current card will be replaced by an updated card that will contain the new setting.
However, what’s actually happening is that the card I expect to update is not updating automatically. To see the change, the user has to manually refresh the app homepage. After, and only after, a manual refresh, does the homepage card update with the new setting.
How do I update the homepage automatically without requiring a manual refresh?
Code.gs
const changedProperty = PropertiesService.getUserProperties().getProperty( MY_SETTING );
const newNavigation = CardService.newNavigation();
const cardPoppedToRoot = newNavigation.popToRoot();
const homepageCard = getCardFromUiConfig( HOMEPAGE_UI_CONFIG, );
const updatedCard = cardPoppedToRoot.updateCard( homepageCard, );
return updatedCard;
I also tried the following code per this answer and the results are exactly the same as with the above code.
Code.gs
return CardService.newActionResponseBuilder()
.setNavigation(
CardService.newNavigation()
.popToRoot()
.updateCard( homepageCard, )
).build();
When I try to configure my appsscript.json file as shown in the answer as follows:
appsscript.json
"homepageTrigger": {
"runFunction": "onHomepage"
},
"contextualTriggers":[
{
"unconditional":{},
"onTriggerFunction": "onHomepage"
}
]
I get the following error:
"appsscript.json" has errors: Invalid manifest: unknown fields: [addOns.common.contextualTriggers]
I think that that is only possible for Gmail add-ons.
contextualTriggers can't be child of common.
From https://developers.google.com/apps-script/manifest/addons#common (links not included):
Common
The manifest configuration for parameters that are common for every host application. Some values defined here are used as a default when specific values for a particular host are omitted.
{
"homepageTrigger": {
object (HomepageTrigger)
},
"layoutProperties": {
object (LayoutProperties)
},
"logoUrl": string,
"name": string,
"openLinkUrlPrefixes": [
string
],
"universalActions": [
{
object (UniversalAction)
}
],
"useLocaleFromApp": boolean
}
AFAIK contextualTriggers can only be used with Gmail add-ons. From https://developers.google.com/apps-script/manifest/gmail-addons (links not included):
Gmail
The Google Workspace add-on manifest configuration for Gmail extensions. See Extending Gmail with Google Workspace add-ons for more information.
{
"authorizationCheckFunction": string,
"composeTrigger": {
object (ComposeTrigger)
},
"contextualTriggers": [
{
object (ContextualTrigger)
}
],
"homepageTrigger": {
object (HomepageTrigger)
}
}
Related
How to fully refresh Google Addon Card (Google Sheets) which includes a drop down menu populated using sheet data when data changes?

Properly implement In-App Updates in App Center?

I am reading this documentation/article from Microsoft on how to Distribute Mobile apps with app center. The problem is I really don't understand how to implement this. I have a app on app center (Android) I want to implement mandatory update so that I can eliminate the bugs of the previous version. I tried to distribute the app with mandatory update enabled and it is not working. How can I fix this?
https://learn.microsoft.com/en-us/appcenter/distribution/
Here is what I did I added this code on my App.xaml.cs (XAMARIN FORMS PROJECT):
protected override void OnStart ()
{
AppCenter.Start("android={Secret Code};", typeof(Analytics), typeof(Crashes), typeof(Distribute));
Analytics.SetEnabledAsync(true);
Distribute.SetEnabledAsync(true);
Distribute.ReleaseAvailable = OnReleaseAvailable;
}
bool OnReleaseAvailable(ReleaseDetails releaseDetails)
{
string versionName = releaseDetails.ShortVersion;
string versionCodeOrBuildNumber = releaseDetails.Version;
string releaseNotes = releaseDetails.ReleaseNotes;
Uri releaseNotesUrl = releaseDetails.ReleaseNotesUrl;
var title = "Version " + versionName + " available!";
Task answer;
if (releaseDetails.MandatoryUpdate)
{
answer = Current.MainPage.DisplayAlert(title, releaseNotes, "Download and Install");
}
else
{
answer = Current.MainPage.DisplayAlert(title, releaseNotes, "Download and Install", "Ask Later");
}
answer.ContinueWith((task) =>
{
if (releaseDetails.MandatoryUpdate || (task as Task<bool>).Result)
{
Distribute.NotifyUpdateAction(UpdateAction.Update);
}
else
{
Distribute.NotifyUpdateAction(UpdateAction.Postpone);
}
});
return true;
}
And here is what I added on my MainActivity.cs(ANDROID PROJECT):
AppCenter.Start("{Secret Code}", typeof(Analytics), typeof(Crashes), typeof(Distribute));
Looking at this App Center documentation here for Xamarin Forms -
You can customize the default update dialog's appearance by implementing the ReleaseAvailable callback. You need to register the callback before calling AppCenter.Start
It looks like you need to swap your current ordering to get in-app updates working.
There could be a lot of different reasons as to why they are not working. As you can see in the Notes here and here,
Did your testers download the app from the default browser?
Are cookies enabled for the browser in their settings?
Another important point you'll read in the links, is that the feature is only available for listed distribution group users. It is not for all your members. You could use a simple version checker for your purpose instead or you could use a plugin.

Is it possible to run a timer task when the application is closed?

I have just completed learning Java, now I am working on creating Android apps. But I am not so expert in this field. I have just created an Android app which has some advertisements like banner ad, interstitial ad. I want to give an opportunity to the user to stop those Ads for 24 hours if they watch a video AD. But I'm not familiar with timer task any suggestion will be very appreciating. here is the code that I imagine :
// load from shared preference
SharedPreference spref = getSharedPreference("directory_name", 0);
if(spref.getBoolean("ad_key", false)==true){
// all ads should stop showing
}else{
// ads are showing
}
// help me here in timer task
As ad reward
--> start countadown
--> if(countDown>0){
doneWatchindAd(true);
}else{
doneWatchindAd(false);
}
// store to shared preference
public void doneWatchindAd(bollean cond){
SharedPreference spref = getSharedPreference("directory_name", 0);
SharedPreference.Editor editor = spref.edit();
editor.putBoolean("ad_key", cond);
editor.commit();
}

Facebook SDK inside iOS app extension cannot find logged in user?

I've created a sample app Share extension. Followed the Apple guides, which means my project consists of a main app and a "share extension" target.
I've setup my Facebook SDK inside the main app, since the app's settings has some FB login/status functionality. It works well according to expectation: users can login and do some shares.
But I also want the logged-in user to be available to the extension target itself. When my extension comes up (in any app), I check Facebook's login status in viewDidLoad:, and it outputs "not logged in":
if ([FBSDKAccessToken currentAccessToken]) {
NSLog(#"logged in");
} else {
NSLog(#"not logged in");
}
The same code outputs "logged in" if called from within the main app. I suspect it has something to do with the fact that the extension target has a different bundle ID that looks like this: .suffix and I guess FB SDK is trying to read the user ID off the keychain cache, but maybe it's reading it off the wrong keychain due to the different bundle IDs... But it could be other reasons as well I guess.
Any idea how to keep Facebook SDK "logged in" inside the extension after the login itself occurred in the containing main app?
I have the exact same problem, as I develop a Message Extension App with a Facebook Login.
To solve the problem, I put the Login Button in the App and use the shared UserDefaults (with a group name) to store a property :
/*
* Get / sets if is FB connected (because we can't use FB SDK in Extension)
*/
public var isFacebookConnected : Bool {
get {
// Getting Bool from Shared UserDefaults
let defaults : NSUserDefaults = NSUserDefaults.init(suiteName: "MY_GROUP_NAME")!
let isFBConnected : Bool? = defaults.boolForKey("IsFacebookConnected")
if isFBConnected == nil {
return false
} else {
return isFBConnected!
}
}
set {
// Setting in UserDefaults
let defaults : NSUserDefaults = NSUserDefaults.init(suiteName: "MY_GROUP_NAME")!
defaults.setBool(newValue, forKey: "IsFacebookConnected")
defaults.synchronize()
}
}
This property is accessed from the App or from the Extension.
Then, in my Login / Logout methods I add :
//FBLogin
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if let error = error {
print(error.localizedDescription)
return
}
if result.isCancelled
{
return
}
// Set in Shared UserDefaults if connected / not connected
ConfigManager.sharedInstance.isFacebookConnected = true
...
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
// OK, keeping track
ConfigManager.sharedInstance.isFacebookConnected = false
}
Then, I keep track of my flag when login / logout.
Warning : this method is not bullet proof as I can't know if Facebook has been uninstalled, but it is robust enough for me.
I believe you'll need to take advantage of Keychain sharing capability in the app and extension to solve this.
https://developer.apple.com/documentation/security/keychain_services/keychain_items/sharing_access_to_keychain_items_among_a_collection_of_apps

Auto-updates to Electron

I'm looking to deploy an auto-update feature to an Electron installation that I have, however I am finding it difficult to find any resources on the web.
I've built a self contained application using Adobe Air before and it seemed to be a lot easier writing update code that effectively checked a url and automatically downloaded and installed the update across Windows and MAC OSX.
I am currently using the electron-boilerplate for ease of build.
I have a few questions:
How do I debug the auto update feature? Do I setup a local connection and test through that using a local Node server or can I use any web server?
In terms of signing the application I am only looking to run apps on MAC OSX and particularly Windows. Do I have to sign the applications in order to run auto-updates? (I managed to do this with Adobe Air using a local certificate.
Are there any good resources that detail how to implement the auto-update feature? As I'm having difficulty finding some good documentation on how to do this.
I am also new to Electron but I think there is no simple auto-update from electron-boilerplate (which I also use). Electron's auto-updater uses Squirrel.Windows installer which you also need to implement into your solution in order to use it.
I am currently trying to use this:
https://www.npmjs.com/package/electron-installer-squirrel-windows
And more info can be found here:
https://github.com/atom/electron/blob/master/docs/api/auto-updater.md
https://github.com/squirrel/squirrel.windows
EDIT: I just opened the project to try it for a while and it looks it works. Its pretty straightforward. These are pieces from my gulpfile.
In current configuration, I use electron-packager to create a package.
var packager = require('electron-packager')
var createPackage = function () {
var deferred = Q.defer();
packager({
//OPTIONS
}, function done(err, appPath) {
if (err) {
gulpUtil.log(err);
}
deferred.resolve();
});
return deferred.promise;
};
Then I create an installer with electron-installer-squirrel-windows.
var squirrelBuilder = require('electron-installer-squirrel-windows');
var createInstaller = function () {
var deferred = Q.defer();
squirrelBuilder({
// OPTIONS
}, function (err) {
if (err)
gulpUtil.log(err);
deferred.resolve();
});
return deferred.promise;
}
Also you need to add some code for the Squirrel to your electron background/main code. I used a template electron-squirrel-startup.
if(require('electron-squirrel-startup')) return;
The whole thing is described on the electron-installer-squirrel-windows npm documentation mentioned above. Looks like the bit of documentation is enough to make it start.
Now I am working on with electron branding through Squirrel and with creating appropriate gulp scripts for automation.
You could also use standard Electron's autoUpdater module on OS X and my simple port of it for Windows: https://www.npmjs.com/package/electron-windows-updater
I followed this tutorial and got it working with my electron app although it needs to be signed to work so you would need:
certificateFile: './path/to/cert.pfx'
In the task config.
and:
"build": {
"win": {
"certificateFile": "./path/to/cert.pfx",
"certificatePassword": "password"
}
},
In the package.json
Are there any good resources that detail how to implement the auto-update feature? As I'm having difficulty finding some good documentation on how to do this.
You don't have to implement it by yourself. You can use the provided autoUpdater by Electron and just set a feedUrl. You need a server that provides the update information compliant to the Squirrel protocol.
There are a couple of self-hosted ones (https://electronjs.org/docs/tutorial/updates#deploying-an-update-server) or a hosted service like https://www.update.rocks
Question 1:
I use Postman to validate that my auto-update server URLs return the response I am expecting. When I know that the URLs provide the expected results, I know I can use those URLs within the Electron's Auto Updater of my Application.
Example of testing Mac endpoint with Postman:
Request:
https://my-server.com/api/macupdates/checkforupdate.php?appversion=1.0.5&cpuarchitecture=x64
JSON Response when there is an update available:
{
"url": "https:/my-server.com/updates/darwin/x64/my-electron=app-x64-1.1.0.zip",
"name": "1.1.0",
"pub_date": "2021-07-03T15:17:12+00:00"
}
Question 2:
Yes, your Electron App must be code signed to use the auto-update feature on Mac. On Windows I'm not sure because my Windows Electron app is code signed and I did not try without it. Though it is recommended that you sign your app even if the auto-update could work without it (not only for security reasons but mainly because otherwise your users will get scary danger warnings from Windows when they install your app for the first time and they might just delete it right away).
Question 3:
For good documentation, you should start with the official Electron Auto Updater documentation, as of 2021-07-07 it is really good.
The hard part, is figuring out how to make things work for Mac. For Windows it's a matter of minutes and you are done. In fact...
For Windows auto-update, it is easy to setup - you just have to put the RELEASES and nupkg files on a server and then use that URL as the FeedURL within your Electron App's autoUpdater. So if your app's update files are located at https://my-server.com/updates/win32/x64/ - you would point the Electron Auto Updater to that URL, that's it.
For Mac auto-update, you need to manually specify the absolute URL of the latest Electron App .zip file to the Electron autoUpdater. So, in order to make the Mac autoUpdater work, you will need to have a way to get a JSON response in a very specific format. Sadly, you can't just put your Electron App's files on your server and expect it to work with Mac just like that. Instead, the autoUpdater needs a URL that will return the aforementioned JSON response. So to do that, you need to pass Electron's Auto Updater feedURL the URL that will be able to return this expected kind of JSON response.
The way you achieve this can be anything but I use PHP just because that's the server I already paid for.
So in summary, with Mac, even if your files are located at https://my-server.com/updates/darwin/x64/ - you will not provide that URL to Electron's Auto Updater FeedURL. Instead will provide another URL which returns the expected JSON response.
Here's an example of my main.js file for the Electron main process of my App:
// main.js (Electron main process)
function registerAutoUpdater() {
const appVersion = app.getVersion();
const os = require('os');
const cpuArchitecture = os.arch();
const domain = 'https://my-server.com';
const windowsURL = `${domain}/updates/win32/x64`;
const macURL = `${domain}/api/macupdates/checkforupdate.php?appversion=${appVersion}&cpuarchitecture=${cpuArchitecture}`;
//init the autoUpdater with proper update feed URL
const autoUpdateURL = `${isMac ? macURL : windowsURL}`;
autoUpdater.setFeedURL({url: autoUpdateURL});
log.info('Registered autoUpdateURL = ' + (isMac ? 'macURL' : 'windowsURL'));
//initial checkForUpdates
autoUpdater.checkForUpdates();
//Automatic 2-hours interval loop checkForUpdates
setInterval(() => {
autoUpdater.checkForUpdates();
}, 7200000);
}
And here's an example of the checkforupdate.php file that returns the expected JSON response back to the Electron Auto Updater:
<?php
//FD Electron App Mac auto update API endpoint.
// The way Squirrel.Mac works is by checking a given API endpoint to see if there is a new version.
// If there is no new version, the endpoint should return HTTP 204. If there is a new version,
// however, it will expect a HTTP 200 JSON-formatted response, containing a url to a .zip file:
// https://github.com/Squirrel/Squirrel.Mac#server-support
$clientAppVersion = $_GET["appversion"] ?? null;
if (!isValidVersionString($clientAppVersion)) {
http_response_code(204);
exit();
}
$clientCpuArchitecture = $_GET["cpuarchitecture"] ?? null;
$latestVersionInfo = getLatestVersionInfo($clientAppVersion, $clientCpuArchitecture);
if (!isset($latestVersionInfo["versionNumber"])) {
http_response_code(204);
exit();
}
// Real logic starts here when basics did not fail
$isUpdateVailable = isUpdateAvailable($clientAppVersion, $latestVersionInfo["versionNumber"]);
if ($isUpdateVailable) {
http_response_code(200);
header('Content-Type: application/json;charset=utf-8');
$jsonResponse = array(
"url" => $latestVersionInfo["directZipFileURL"],
"name" => $latestVersionInfo["versionNumber"],
"pub_date" => date('c', $latestVersionInfo["createdAtUnixTimeStamp"]),
);
echo json_encode($jsonResponse);
} else {
//no update: must respond with a status code of 204 No Content.
http_response_code(204);
}
exit();
// End of execution.
// Everything bellow here are function declarations.
function getLatestVersionInfo($clientAppVersion, $clientCpuArchitecture): array {
// override path if client requests an arm64 build
if ($clientCpuArchitecture === 'arm64') {
$directory = "../../updates/darwin/arm64/";
$baseUrl = "https://my-server.com/updates/darwin/arm64/";
} else if (!$clientCpuArchitecture || $clientCpuArchitecture === 'x64') {
$directory = "../../updates/darwin/";
$baseUrl = "https://my-server.com/updates/darwin/";
}
// default name with version 0.0.0 avoids failing
$latestVersionFileName = "Finance D - Tenue de livres-darwin-x64-0.0.0.zip";
$arrayOfFiles = scandir($directory);
foreach ($arrayOfFiles as $file) {
if (is_file($directory . $file)) {
$serverFileVersion = getVersionNumberFromFileName($file);
if (isVersionNumberGreater($serverFileVersion, $clientAppVersion)) {
$latestVersionFileName = $file;
}
}
}
return array(
"versionNumber" => getVersionNumberFromFileName($latestVersionFileName),
"directZipFileURL" => $baseUrl . rawurlencode($latestVersionFileName),
"createdAtUnixTimeStamp" => filemtime(realpath($directory . $latestVersionFileName))
);
}
function isUpdateAvailable($clientVersion, $serverVersion): bool {
return
isValidVersionString($clientVersion) &&
isValidVersionString($serverVersion) &&
isVersionNumberGreater($serverVersion, $clientVersion);
}
function getVersionNumberFromFileName($fileName) {
// extract the version number with regEx replacement
return preg_replace("/Finance D - Tenue de livres-darwin-(x64|arm64)-|\.zip/", "", $fileName);
}
function removeAllNonDigits($semanticVersionString) {
// use regex replacement to keep only numeric values in the semantic version string
return preg_replace("/\D+/", "", $semanticVersionString);
}
function isVersionNumberGreater($serverFileVersion, $clientFileVersion): bool {
// receives two semantic versions (1.0.4) and compares their numeric value (104)
// true when server version is greater than client version (105 > 104)
return removeAllNonDigits($serverFileVersion) > removeAllNonDigits($clientFileVersion);
}
function isValidVersionString($versionString) {
// true when matches semantic version numbering: 0.0.0
return preg_match("/\d\.\d\.\d/", $versionString);
}

Resources