I get the error INVALID_REQUEST when i try to show a IMInterstitialAdView.
I run the app on real device, no in test mode.
I deployed the app on my device via titanium store, no google play for now.
Here the code:
var Inmobi = require('ti.inmobi.ad');
Inmobi.setLogLevel(1);
Inmobi.sendAppTrackerConversion("dd1efdd608c7424cbd675f55d8f5a0f1");
var request = Inmobi.createIMAdRequest({
//locationInquiryAllowed : true,
// currentLocation: undefined,
testMode : false
});
var inmobiInter = Inmobi.createIMInterstitialAdView({
// activity: currentActivity,
imAppId : "dd1efdd608c7424cbd675f55d8f5a0f1"
});
var currActivity = Titanium.Android.currentActivity;
inmobiInter.load(currActivity);
// listener for onAdRequestLoaded
inmobiInter.addEventListener("onAdRequestLoaded", function() {
alert("Ad request loaded");
Ti.API.info("Ad request loaded");
});
// listener for onAdRequestFailed
inmobiInter.addEventListener("onAdRequestFailed", function(e) {
alert("Ad request failed, error Code: " + e.errorCode);
Ti.API.info("Ad request failed, error Code: " + e.errorCode);
});
// listener for onShowAdScreen
inmobiInter.addEventListener("onShowAdScreen", function() {
alert("Show Ad Screen");
Ti.API.info("Show Ad Screen");
});
// listener for onDismissAdScreen
inmobiInter.addEventListener("onDismissAdScreen", function() {
alert("Dismiss Ad screen");
Ti.API.info("Dismiss Ad screen");
});
// listener for onLeaveAdScreen
inmobiInter.addEventListener("onLeaveApplication", function() {
alert("Leave Application");
Ti.API.info("Leave Application");
});
inmobiInter.loadNewAd(request);
self.add(inmobiInter);
Ti.API.info('======================================================');
// listener
buttonMPView.addEventListener('click', function() {
Ti.API.info('------------> ' + inmobiInter.getState());
if (inmobiInter.getState() == inmobiInter.State_READY) {
inmobiInter.show();
} else {
Ti.API.info("State is not " + inmobiInter.State_READY + ", State is: "
+ inmobiInter.getState());
}
if(Titanium.Network.networkType == Titanium.Network.NETWORK_NONE){
alert("Nessuna connessione internet presente.")
}else{
self.fireEvent('clickButtonMPView')
}
});
Any hint?
Thank you
I am Naresh and I work for InMobi.
You are using the older plugin and we don't recommend that.
Please use the following updated InMobi plugin for Titanium. Documentation is on the same page. It also includes InMobi analytics.
http://www.inmobi.com/support/art/23846096/22114287/appcelerator-partner-platform-integration-guide/
Do let me know if you have questions.
thanks
Related
I am trying to learn to use azure mobile app, but I am having serious problems in using the NotificationHub. I have an Imagine subscription to Azure. I creating an android mobile app with azure backend. I have created a notification hub associated to the azure mobile app on the azure portal.
To register the app on the notification hub I used the code in this tutorial:
https://learn.microsoft.com/en-gb/azure/notification-hubs/notification-hubs-android-push-notification-google-fcm-get-started
The users are authenticated on the azure backend previuosly by using their google account, microsoft account or facebook account. New users are inserted into the table Users by the following node js code written for the table script Users.js. I want a push notification to Welcome the new User.
var azureMobileApps = require('azure-mobile-apps');
var logger = require('azure-mobile-apps/src/logger');
var table = azureMobileApps.table();
table.access = 'authenticated';
/**
* Adds the email address from the claims to the context item - used for
* insert operations
* #param {Context} context the operation context
* #returns {Promise} context execution Promise
*/
function addEmailToContext(context) {
/*
* Getting claim fields
*/
return context.user.getIdentity().then((data) => {
if( data.microsoftaccount != undefined){
context.item.email = data.microsoftaccount.claims.emailaddress;
context.item.name = data.microsoftaccount.claims.givenname;
context.item.surname = data.microsoftaccount.claims.surname;
}
if( data.google != undefined){
context.item.email = data.google.claims.emailaddress;
context.item.name = data.google.claims.givenname;
context.item.surname = data.google.claims.surname;
context.item.picture_url = data.google.claims.picture;
}
if( data.facebook != undefined){
context.item.email = data.facebook.claims.emailaddress;
context.item.name = data.facebook.claims.givenname;
context.item.surname = data.facebook.claims.surname;
}
logger.info('[tables/Users.js] --> NEW USER REGISTERED:'
+'\n\t Name:'+context.item.name
+'\n\t Surname:'+context.item.surname
+'\n\t Email:'+context.item.email);
// Execute the insert. The insert returns the results as a Promise,
// Do the push as a post-execute action within the promise flow.
return context.execute()
.then(function (results) {
// Only do the push if configured
if (context.push) {
// Mobile Apps adds a user tag when registering for push notifications
// Define the GCM payload.
var payload = {
"data": {
"message": 'Welcome '+context.item.username
}
};
context.push.gcm.send(context.user.id, payload, function (error) {
if (error) {
logger.error('Error while sending push notification: ', error);
} else {
logger.info('Push notification sent successfully!');
}
});
}
// Don't forget to return the results from the context.execute()
return results;
})
.catch(function (error) {
logger.error('Error while running context.execute: ', error);
});
});
}
// CREATE - add or overwrite the authenticated user
table.insert(addEmailToContext);
module.exports = table;
According to "How to: Send push notifications to an authenticated user using tags" in the tutorial on How to use the Azure Mobile Apps Node.js SDK
"When an authenticated user registers for push notifications, a user ID tag is automatically added to the registration. "
So in the Users.js, as suggested in this tutorial I wrote the following code to send the push notification to the user.
context.push.gcm.send(context.user.id, payload, function (error) {
if (error) {
logger.error('Error while sending push notification: ', error);
} else {
logger.info('Push notification sent successfully!');
}
});
With this code the push notification results to be sent successfully, but the device doesn't receive any notifications. If I use null instead of context.user.id then all devices receive the push notification correctly:
context.push.gcm.send(null, payload, function (error) {
if (error) {
logger.error('Error while sending push notification: ', error);
} else {
logger.info('Push notification sent successfully!');
}
});
I also tried to invoke the following custom API to create tag when the user is registered to the hub. The invoked API is the following:
var logger = require('azure-mobile-apps/src/logger');
exports.post = function(req, res) {
logger.info('[api/registerTag.js] --> Invoked');
// Get the notification hub used by the mobile app.
var push = req.azureMobile.push,
installationId = req.get('X-ZUMO-INSTALLATION-ID'),
tags = req.body.tag.toString();
// Define an update tags operation.
var updateOperation = [{
"op": "add",
"path": "/tags",
"value": tags
}];
// Update the installation to add the new tags.
push.patchInstallation(installationId, updateOperation, function(error) {
if(error){
logger.error('[api/registerTag.js] --> An error occurred while adding'
+'the following tags: \n\t'+tags, error);
res.status(error.statusCode).send(error.detail);
} else {
logger.info('[api/registerTag.js] --> The following tags have been added'
+'to the Notification Hub: \n\t'+tags, error);
res.status(200).send(tags);
}
});
};
On the console it is printed that the tag has been added successfully. But if I then modify the Users.js code like this:
...
// Only do the push if configured
if (context.push) {
// Mobile Apps adds a user tag when registering for push notifications
var userTag = '_UserId:' + context.user.id;
logger.info("TAG "+userTag);
// Define the GCM payload.
var payload = {
"data": {
"message": 'Welcome '+context.item.username
}
};
context.push.gcm.send(userTag, payload, function (error) {
if (error) {
logger.error('Error while sending push notification: ', error);
} else {
logger.info('Push notification sent successfully!');
}
});
}
...
again nothing is received. I have also tried whitelisting tags or adding them automatically using the Push section of the mobile app like shown in the image:
IMAGE LINK: i.stack.imgur.com/KBvQI.png
But the problem is still there. Hope someone can help me. Thanks.
After several times of testing, I succeeded in reproducing your issue and got the same problem. To achieve your requirement I did some modification in Android client-end:
1, Cache authentication user in the MainActivity class. Following is my code snippet. For more details you can refer here.
public static final String SHAREDPREFFILE = "temp";
public static final String USERIDPREF = "uid";
public static final String TOKENPREF = "tkn";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Create the Mobile Service Client instance, using the provided Mobile Service URL and key
mClient = new MobileServiceClient(
"https://yourwebsitename.azurewebsites.net",
this).withFilter(new ProgressFilter());
// Extend timeout from default of 10s to 20s
mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() {
#Override
public OkHttpClient createOkHttpClient() {
OkHttpClient client = new OkHttpClient();
client.setReadTimeout(20, TimeUnit.SECONDS);
client.setWriteTimeout(20, TimeUnit.SECONDS);
return client;
}
});
authenticate();
} catch (MalformedURLException e) {
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
} catch (Exception e){
createAndShowDialog(e, "Error");
}
}
private void authenticate() {
// We first try to load a token cache if one exists.
if (loadUserTokenCache(mClient)) {
createTable();
register();
}
// If we failed to load a token cache, login and create a token cache
else {
// Login using the Google provider.
ListenableFuture<MobileServiceUser> mLogin = mClient.login(MobileServiceAuthenticationProvider.Google);
Futures.addCallback(mLogin, new FutureCallback<MobileServiceUser>() {
#Override
public void onFailure(Throwable exc) {
createAndShowDialog("You must log in. Login Required", "Error");
}
#Override
public void onSuccess(MobileServiceUser user) {
createAndShowDialog(String.format("You are now logged in - %1$2s", user.getUserId()), "Success");
cacheUserToken(mClient.getCurrentUser());
createTable();
register();
}
});
}
}
private void cacheUserToken(MobileServiceUser user) {
SharedPreferences prefs = getSharedPreferences(SHAREDPREFFILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(USERIDPREF, user.getUserId());
editor.putString(TOKENPREF, user.getAuthenticationToken());
editor.commit();
}
private void register() {
NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, MyHandler.class);
registerWithNotificationHubs();
}
2, In RegistrationIntentService class replace regID = hub.register(FCM_token).getRegistrationId(); with the following code:
regID = hub.register(FCM_token, prefs.getString("uid", "")).getRegistrationId();
3, Make sure add the line below to the first line within onHandleIntent method.
SharedPreferences prefs = getSharedPreferences("temp", Context.MODE_PRIVATE);
We are working on hydrid apps. Recently we got the requirement to support voice sms. We did R&D on that but we didn't have any luck. So we are trying to record 1 minute voice then we send it to a server. We don't know is it correct way. Please guide to us.
We tried like this https://www.npmjs.com/package/cordova-plugin-audio-recorder-api
var recorder = new Object;
function stop(){
recorder.stop = function() {
window.plugins.audioRecorderAPI.stop(function(msg) {
// success
alert('ok: ' + msg);
}, function(msg) {
// failed
alert('ko: ' + msg);
});
}}
function record{
recorder.record = function() {
window.plugins.audioRecorderAPI.record(function(msg) {
// complete
alert('ok: ' + msg);
}, function(msg) {
// failed
alert('ko: ' + msg);
}, 30); // record 30 seconds
}}
function playback(){
recorder.playback = function() {
window.plugins.audioRecorderAPI.playback(function(msg) {
// complete
alert('ok: ' + msg);
}, function(msg) {
// failed
alert('ko: ' + msg);
});
}}
We please guide to proper way to achieve our task.
I am developing android app using cordova on Ubuntu 14. Its a hybrid app that consists of:-
Server- RESTful api using Php with slim framework &
Client - Backbone with requirejs,jquery,bootstrap etc.., HTML,CSS.
I have created the app as per the steps given in Apache Cordova Documentation guide (http://cordova.apache.org/docs/en/5.0.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide) and imported the app in android studio. I am using android studio 1.3.
I have connected the app to my localhost using(10.0.2.2), the app runs on the emulator and shows the 'login' screen.
The challange is, after filling user name and password, when I click 'Sign In' it should trigger http 'POST' as in Browser app. But it does not triggers POST and in return I get 404 error in Backbone.sync-error, and when I saw the server HTTP_METHOD it shows 'GET' !!
I have overriden Backbone.sync method.
This is my 'login.js' file triggering the event
//sigin button click code ...
// ...
signinInfo.set({
email: email,
password: password
});
signinInfo.save(null,{
success: function (data) {
window.localStorage.setItem('uid',signinInfo.attributes.uid);
window.localStorage.setItem('email_id',signinInfo.attributes.email_id);
// redirect the user to the given route
if (data.attributes.status == "1") {
window.location.href = "";
} else {
alert("Incorrect password!");
}
} // success
});
The above 'save' on 'signinInfo' model triggers the Backbone.sync method. Here's the code snippet from models.js that overrides 'Backbone.sync' method:
originalSync = Backbone.sync;
Backbone.sync = function (method, model, options) {
var success = options.success;
var error = options.error;
console.log("Models.js- method: " + method + ", model: " + JSON.stringify(model) + ", options: " + JSON.stringify(options));
options.success = function (model, response, options) {
console.log("Models.js- success, response: " +response );
$('.srLoading').hide();
if (typeof model.redirect == 'undefined') {
success(model, response, options);
} else {
window.location.replace("/");
}
};
options.error = function (model, response, options) {
console.log("Models.js- error:" +JSON.stringify(model) + " response: " + response + "; options: " + JSON.stringify(options));
$('.srLoading').hide();
error(model, response, options);
};
// I have tried to put options for crossDomain here, but its not working
options = options || (options = {});
if (!options.crossDomain) {
options.crossDomain = true;
}
if (!options.xhrFields) {
options.xhrFields = {withCredentials:true};
}
if (method === "read") {
console.log("Models.js- read method!" );
$('.srLoading').show();
options.dataType = "jsonp";
return originalSync.apply(Backbone, arguments);
}
if (method === "create") {
console.log("Models.js- create method!" );
$('.srLoading').show();
options.dataType = "jsonp";
options.contentType = 'application/json';
options.type = 'POST';
//options.data = JSON.stringify(options.data);
return originalSync.apply(Backbone, arguments);
}
if (method === "update") {
$('.srLoading').show();
options.dataType = "jsonp";
return originalSync.apply(Backbone, arguments);
}
if (method === "delete") {
$('.srLoading').show();
options.dataType = "jsonp";
return originalSync.apply(Backbone, arguments);
}
}; //Backbone.sync
Above, method 'create' is called but at server it does not converts to 'POST' request. Instead $_SERVER['REQUEST_METHOD'] shows 'GET'! :(
In my Backbone.sync method I commented [options.dataType = "jsonp";] so that the code looks as follows:
...
if (method === "create") {
console.log("Models.js- create method!" );
$('.srLoading').show();
//options.dataType = "jsonp";
options.contentType = 'application/json';
return originalSync.apply(Backbone, arguments);
}
Now my login sends HTTP POST request to the server!
On cross domain (CORS), backbone with dataType 'jsonp' can only make 'GET' request. So to make other actions we need to send 'json' data.
I'm using
function Global_Events_OnStart(e) {
isNetworkUp = (Device.connectionType == 0);
}
to detect if network connected. At Home Screen's onShow event which hosts code to run Webclients:
function pgHome_Self_OnShow() {
if (isNetworkUp) {
wcPersonList.run(true); // async run
wcImages.run(true);
}else{
Dialogs.dlConnectionWarning.show();
}
}
Is this ok? Or should I add additional controls to Global Application.onError event?
With using isNetworkUp control you can use your own Error Dialog.
If you don't write any codeLines to detect that network is up or down,
It triggers Global_Events_OnError .
function Global_Events_OnError(e) {
switch (e.type) {
case "Server Error":
case "Size Overflow":
alert(lang.networkError);
break;
default:
SES.Analytics.eventLog("error", JSON.stringify(e));
//change the following code for desired generic error messsage
alert({
title : lang.applicationError,
message : e.message + "\n\n*" + e.sourceURL + "\n*" + e.line + "\n*" + e.stack
});
break;
}
}
Global_Events_OnError is predefined function to detect any kind of error in your project.
Smartface.io Team
i have a problem with titanium to comunicate with a my server in the network,
the server's ip is 192.168.0.208 on the port 8000 (is a Node.js server).
If i call the server from the browser no problem but if i try to call the server from the application in Titanium i saw this error "The target server failed to respond" and in the server log no call is received
this is my network.js file in the application
function HttpRequest(url, type, args, functionOnSuccss,functionOnError,timeout) {
// args is json parameters OPTIONAL
Ti.API.log("[HTTP REQ] Call" + url);
// ---# ok string ------
var xhr = Titanium.Network.createHTTPClient();
xhr.open(type,url);
xhr.cache = false;
xhr.enableKeepAlive = false;
xhr.timeout = timeout ? timeout : 500000;
xhr.setRequestHeader("Content-type", "application/json");
// xhr.setRequestHeader("Cookie", 'JSESSIONID=' + cookie + '');
xhr.onload = function(e) {
Ti.API.info("[HTTP] Response" + this.responseText);
functionOnSuccss(this.responseText);
};
xhr.onerror = function(e) {
Ti.API.info("ERROR " + e.error);
// alert("Connection Error");
functionOnError(e.error);
};
if(args){
xhr.send(args);
}else{
xhr.send();
}
};
exports.request = HttpRequest;
and this is the coda that make the request
network = require('/library/network');
var sendCarrello = function() {
$.loader.visible = true;
$.carrelloCamminante.animate(a);
url = "192.168.0.208:8000/newMobileUser"; // or http://192.168.0.208:8000/newMobileUser it's the same
network.request(url, "get",undefined, function(resp) {
alert(resp);
$.loader.visible = false;
}, function(err) {
alert("error - "+""+err);
});
};
what could be the error?
You must use "GET" not "get" :
network.request(url, "GET",undefined, function(resp) { ....