I have added plugin of google adwords in my PhoneGap application. what should i do to see that plugin is working as i am new to the PhoneGap .how and where will i see the changes in my application after adding that plugin to my application.. can i see any logo of adwords or anything .. please help i tried this
this is d code in plugin
public class CordovaGoogleAdWords extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
//PluginResult result = null;
//callbackContext.sendPluginResult(result);
if(action.equals("track")) {
this.track(inputs, callbackContext);
return true;
}
return false;
}
private void track(JSONArray inputs, CallbackContext callbackContext) {
try {
AdWordsConversionReporter.reportWithConversionId(
this.cordova.getActivity().getApplicationContext(),
inputs.getJSONObject(0).getString("conversionId"),
inputs.getJSONObject(0).getString("label"),
inputs.getJSONObject(0).getString("value"), // The value of your conversion; can be modified to a transaction-specific value.
Boolean.parseBoolean(inputs.getJSONObject(0).getString("repeatable"))
);
callbackContext.success();
} catch (JSONException e) {
Log.d("Cordova Plugin Error", e.getMessage());
e.printStackTrace();
callbackContext.error("Unable to send tracking data");
}
}
}
For mobile ads use AdMob. You can use an existing plugin for phonegap/cordova: https://github.com/appfeel/admob-google-cordova:
For a cordova / phonegap CLI project, use one of this command line instructions:
cordova plugin add com.admob.google
phonegap local plugin add com.admob.google
If you use Phonegap build, place the following tag in your config.xml file:
<gap:plugin name="com.admob.google" source="plugins.cordova.io" />
Then in your javascript code:
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
// Set AdMobAds options:
admob.setOptions({
publisherId: "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB", // Required
interstitialAdId: "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII", // Optional
tappxIdiOs: "/XXXXXXXXX/Pub-XXXX-iOS-IIII", // Optional
tappxIdAndroid: "/XXXXXXXXX/Pub-XXXX-Android-AAAA", // Optional
tappxShare: 0.5 // Optional
});
// Start showing banners (atomatic when autoShowBanner is set to true)
admob.createBannerView();
// Request interstitial (will present automatically when autoShowInterstitial is set to true)
admob.requestInterstitial();
}
document.addEventListener("deviceready", onDeviceReady, false);
Related
I have a simple string "twist" being passed on from the backend which is not a urlimage of simulator
My code for linking is as follows
console.log(url);
let linkOpened = false;
Linking.canOpenURL(url).then((canOpen) => {
console.log("canOpen : ", canOpen);
if (canOpen) {
Linking.openURL(url);
linkOpened = true;
} else {
console.log("i am calling");
}
});
As we can see "twist" is a string and not a URL which cannot be opened.
The same code on android emulator returns false which is the correct result but true on IOS which is incorrect
IOS Watchman Output
None of the answers on github/stackoverflow/apple dev forums work for me
I have also added this in my info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>twist</string>
<string>nothing</string>
</array>
Running on
XCODE 14
Node 165.13.0
Kindly assist me. :)
Linking on backend using
https://developer.apple.com/documentation/uikit/uiapplication/1622952-canopenurl
It is directly linking ios nsurl TO javascript string which is causing error
for now use following code and wait for there update
const url = 'twist:';
console.log(url);
let linkOpened = false;
if (url.search(':') != -1) {
console.log('url', url.search(':'));
try {
linkOpened = await Linking.canOpenURL(url);
} catch (error) {}
}
console.log('linkOpened', linkOpened);
I have an Angular (v10) WebApp, which handles the X-CSRF-TOKEN cookie correctly as explained in the Angular Guide by using the HttpClientXsrfModule in my imports, i.e.:
// app.module.ts
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
}),
and by setting an relative Path in my services' requests, like:
// some service.ts
public deleteX(x_id: number): Observable<any> {
return this.httpClient.delete(`api/X/${x_id}`);
}
and now, the browser itself handles fetching the token from the server and sending it by each subsequent POST/DELETE/PUT/PATCH request successfully.
However, if I compile the application now to an Android app using cordova, the app sends a request (with x_id=1068) to file:///android_asset/www/api/X/1068.
I can modify my http services to use platform-specific absolute/relative paths easily, such as:
// some service.ts
public deleteX(x_id: number): Observable<any> {
if (this.cordovaService.platform === CordovaService.PLATFORM_ANDROID) {
return this.httpClient.delete(`${environment.baseUrl}/api/X/${x_id}`);
} else {
return this.httpClient.delete(`api/X/${x_id}`);
}
}
But then, my request's response from the Android application is
error: "access_denied"
error_description: "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'."
What can I do, to add correct handling of the X-XSRF-TOKEN for my cordova compiled Android app?
I ended up using the cordova-plugin-advanced-http, that is offering a response-cookie-fetching opportunity described here.
I've created a generic-http-service containg generic methods for each of the HTTP methods (GET,HEAD,PATCH,PUT,POST,DELETE), that is first checking for the running platform and then forwarding an adjusted request.
example for generic GET (pseudo-code):
// generic-http-service.ts
public get<T>(url: string, queryParams?: any): Observable<T> {
if (this.cordovaService.platform === CordovaService.PLATFORM_ANDROID) {
// android-specific solution
// 1. adjust params
// 2. set general headers + the XSRF-TOKEN from the previous sendt request
// 3. return Observable(obs) {
// 4. send:
cordova.plugin.http.get(`${environment.baseUrl}/${url}`, adjustedParams, adjustedHeaders,
successResponse => {
// 5. fetch & save XSRF-TOKEN
obs.next(JSON.parse(successResponse.data) as T);
}, errorResponse => {
obs.error(errorResponse);
})
}
} else {
// web-specific solution based on the angular guide
return this.httpClient.get(`${url}`);
}
}
Afterwards I just needed to adjust my services a little bit.
I am working on Cordova app. I wannt to implement a qrcode reader. I tried plugins available in Cordova but they all are buggy and some doesnot provide preview of scanner/video on same screen.
So I decided to use instascan which is a js based library to be used with webcams. I used it and implemented it in a simple cordova app and its working.
Now I see preview of my scan (camera video which is currently being scanned) and it scans perfectly.
But later I merged that code with my actual Cordova app which uses Vue cli. Now I am getting:
Error: Cannot access video stream (NotReadableError)
This error is probably (as I read) due to Chrome's https policy. But the problem is, Cordova uses webview and another cordova app which is basic cordova instance with this plugin only is working perfectly.
My implementation:
mounted: function () {
var _this = this;
this.$ons.ready(function () { // this is ready event fired by Onsen UI when cordova's native APIs are loaded
var scanner = new Instascan.Scanner({
continuous: true,
mirror: false,
video: document.getElementById('scannerPreview'),
});
scanner.addListener('scan', function (content) {
alert('scan' + content);
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
if (cameras.length === 1) {
scanner.start(cameras[0]);
} else {
scanner.start(cameras[1]);
}
scanner.start(cameras[0]);
} else {
alert('No cameras found.');
}
}).catch(function (e) {
alert(e);
});
});
},
first add the permissions plugin:
cordova plugin add cordova-plugin-permission
And then you must request the permits in the camera:
permissions.requestPermission(permissions.CAMERA, success, error);
function error() {
return false;
}
function success( status ) {
if( !status.hasPermission ) error();
return true;
}
I just builded an app by ionic-framework. The server side is:
bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity
All function works fine in the PC chrome browser, authorization pass and request all get correct response.
Request success screen
but once we builded the html5 and angularjs files into apk, function fails.
ionic build android
ionic run android
Got the Error screen by chrome inspect plugin.
There a similar question here. I also tried that way but also can't work.
Client-Via:shouldInterceptRequest
In index.html file there a cross domain js reference also failed.
I find this might relate to shouldInterceptRequest method in SystemWEbViewClient.java
I common few no use code and just direct response the result, finally the js reference successed.
but the auth request still failed
and I am not sure whether this is a best way to solve the problem.
I just comment the code below which in shouldInterceptRequest method, then it all works.
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
// *********************** below four lines of code commented.-----
// if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
// LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
// return new WebResourceResponse("text/plain", "UTF-8", null);
// }
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
I have a following code in native android
List<PackageInfo> PackList = getPackageManager().getInstalledPackages(0);
for (int i=0; i < PackList.size(); i++)
{
PackageInfo PackInfo = PackList.get(i);
if ( ( (PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true)
{
String AppName = PackInfo.applicationInfo.loadLabel(getPackageManager()).toString();
Log.e("App" + Integer.toString(i), AppName);
}
}
for getting information about installed application in mobile. I want to use in cordova/phonegap application.
How I use that?
What steps do I need?
Or is there anyway that same code use in different platforms
(android,windows)?
I also checked this link but didn't understand
Thanks In Advance
To use native code in a phonegap app you have to create a phonegap plugin. This is actually pretty simple:
1) Create you phonegap plugin class, in this case the plugin only responds to the action "toast" to create a native Android toast:
public class ExamplePlugin extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if("toast".equals(action)) {
// The first String in the arguments array is the text for the toast
String text = args.getString(0);
Toast toast = Toast.makeText(this.cordova.getActivity(), text, Toast.LENGTH_SHORT);
toast.show();
// With PluginResult you can send results back to the js layer.
PluginResult result = new PluginResult(PluginResult.Status.OK, "--toast displayed.");
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
// Return true if everything worked as it should. If an error occurs return false.
// Depending on this return value either the success or error callback is invoked.
return true;
}
#Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
// Here you can perform some initialisations for your plugin.
}
}
Then in the config.xml of your phonegap app you add this line:
<plugin name="ExamplePlugin" value="com.phonegap.example.ExamplePlugin" />
Name being the name by which you can call the plugin from javascript and value being the complete class name of your plugin.
Now you can call the plugin from javascript:
cordova.exec(successCallback, errorCallback, "ExamplePlugin", "toast", ["Hello Cordova!!1"]);
You supply two callbacks, the name of the plugin you want to call, the action you want to execute and an array of arguments, in our case the plugin is named "ExamplePlugin" the action is "toast" and we only have on string argument as text for our toast.
Of course this just works for Android. If you want the same functionality for different platforms e.g. iOS, Windows Phone etc. You are gonna have to create a plugin for each of them too.
You will need to create a PhoneGap/Cordova plugin.
In the return data (the result) in the plugin you need to return the String.
For recent an example, check out this blog post. It works with AndroidPreferences feature and it uses both sending data and retrieving data.