Get IMEI of an android phone on page load - android

I am developing an application in Cordova which requires to get the IMEI number of any device programatically. I want want get the IMEI on page load and store it on local storage
$(function(){
$('#LoginForm').submit(function(){
var loginData = $ ("#LoginForm").serialize();
$.ajax({
type: 'post',
url: "http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
data: loginData,
crossDomian: true
}).done(function (data) {
console.log(data);
alert(data.cMessage.code)
if(data.cMessage.code == "0"){
window.location.href = "Home.html"
}
else{
window.location.href = "Payment.html"
}
}).error(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText || textStatus);
});
return false;});
})

If you're looking for a unique number to identify the device, then you can use this:
android.os.Build.SERIAL;

You can simply use the cordova plugin device to optain the unique identifier of any cordova supported OS.
//Get the device's Universally Unique Identifier
var string = device.uuid;

Related

Deep link routing to Android/IOS app in vue js

When the user visits the mobile website via android/ios iphone, it should be redirected respective apps in their phone. If they still didn't install the respective apps for the websites, they should be redirected to respective apps in play store or apple store. Inside App.vue file below changes are done.
const userAgent = window.navigator.userAgent;
const isIphone = userAgent.match(/iPhone/);
const isAndroid = userAgent.match(/Android/);
const isIpad = userAgent.match(/iPad/);
beforeCreate: function() {
if ((isIphone === "iPhone" || isAndroid === "Android") && isIpad === "null") {
window.location = `{yourApp}:///`;
}
},
created: function() {
if (isIphone || isAndroid) {
setTimeout(() => {
if (isIphone === "iPhone") {
window.location.href = "https://apps.apple.com/app/id{<app id>}"; //here add your correct app id
} else if (isAndroid === "Android") {
window.location.href =
"https://play.google.com/store/apps/details?id=<app id>"; //here add your correct app id
}
}, 2500);
}
}
But it won't work as I expected. I guess reason could be device identification issue. Anyone knows how to solve this issue or any other approach to do deep linking in vue js?
userAgent.match() will return an Array type. Then in beforeCreate hook you're checking if those consts are strings, but they are arrays possibly carrying those strings inside them. You also perform similar checks in the created hook. That is probably why your statements never execute.

Cannot send image in base64 format with XHR to aws S3 in android(react-native)

I got very strange issue: we have scan functionality for documents in our app and as the result scan give's me encoded base64 image with photo. Everything is good on ios platform but when I trying to send my picture on android, I get xhr.status 0 and error. Also, next strange thing is that when I starting debug mode and enable network inspection in react-native-debugger, picture is sending without errors. I was trying it on release app version, installed on my device, but still got an error with status 0
XHR request
export const uploadXHRImage = (url: string, data: IDataUploadImage) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve('Image successfully uploaded to S3');
} else {
reject(localize('failedUploadImage'));
}
}
};
xhr.ontimeout = () => reject(localize('timeoutUploadImage'));
xhr.timeout = UPLOAD_IMAGE_TIMEOUT;
xhr.open('PUT', url);
xhr.setRequestHeader('Content-Type', data.type);
xhr.send(data);
});
};
Add to header:
"Content-Type": 'application/json',
"Connection": "close",
I found the answer: Android can not process xhr send image, while image isn't saved as file in cache or other directory. Also, android needs file:// before data. Example is here:
saveImage = (image: string) => {
if (IS_IOS) {
return `data:image/jpg;base64,${image}`;
}
const tempFileDirectory = `${fs.CachesDirectoryPath}`;
const tempFilePath = `${tempFileDirectory}/${uuidv4()}.jpg`;
fs.writeFile(tempFilePath, image, 'base64');
return `file://${tempFilePath}`;
};

How to query user pool from cognito with lambda functions using Amplify-android AWS

I have this function signature on schema.graphql, can I used it in order to call to lambda function that retrieve user list from Cognito server?
type Query
{
echo(msg: String): String #function(name: "getUsers-${env}")
}
How can I call it from Android ?
Do I need Apollo ?
Does Amplify library it's enough ?
Basically you can't query users from Cognito Amazon server directly using the schema.
In the Android application you must create and use the following Amplify plugins, you can read more about it from here:
https://docs.amplify.aws/start/q/integration/android
You must create lambda function as describe here:
const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18', region: 'eu-central-1'});
exports.handler = async (event) => {
// TODO implement
let users = [];
let roles = ['admin', 'user' ];
try
{
// (let i=0, len=roles.length; i<len; i++)
//{
//const role = roles[i];
let more = true;
let nextToken = '';
while (more)
{
let params = {
UserPoolId: "your pool id",
//GroupName: role,
Limit: 60
};
if (nextToken !== '')
{
params.NextToken = nextToken;
}
const rawUsers = await cognito.listUsers(params).promise();
const mapUsers = rawUsers.Users.map(user => {
let atts = {};
for (const att of user.Attributes)
{
atts[att.Name] = att.Value;
}
return {
username: user.Username,
name: atts.hasOwnProperty('name') ? atts.name : '',
email: atts.hasOwnProperty('email') ? atts.email : '',
status: user.UserStatus,
//role: role
};
});
users= users.concat(mapUsers);
if (rawUsers.hasOwnProperty('NextToken')) {
nextToken = rawUsers.NextToken;
} else {
more = false;
}
}
// }
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
// headers: {
// "Access-Control-Allow-Origin": "*"
// },
body: JSON.stringify(users),
};
return response;
}
catch(e)
{
const response = {
statusCode: 500,
// Uncomment below to enable CORS requests
// headers: {
// "Access-Control-Allow-Origin": "*"
// },
body: e,
};
return response;
}
};
Then create REST api:
Use the terminal Amplify CLI commands and connect it to the lambda function that was created including "Authenticated users only".
Run:
amplify add api
C:\DOV_AWS>amplify api add
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the
project: users
? Provide a path (e.g., /book/{isbn}):
C:\DOV_AWS>amplify api add
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the
project: DOV
? Provide a path (e.g., /book/{isbn}): /users
? Choose a Lambda source Use a Lambda function already added in the current Amplify projec
t
? Choose the Lambda function to invoke by this path getUsers
? Restrict API access Yes
? Who should have access? Authenticated users only
? What kind of access do you want for Authenticated users? create, read, update, delete
? Do you want to add another path? No
Successfully added resource DOV locally
Use the amplify push command:
amplify push
In order to update the API on the cloud.
Run the following code in your app in order to fetch the users.
RestOptions options = RestOptions.builder()
.addPath("/users")
.build();
Amplify.API.get("Users", options, response ->
Log.i("MyAmplifyApp", " ! ! ! ! ! Data Respond ! ! ! ! !"
+ response.getData().asString()),
error -> Log.e("MyAmplifyApp", "GET failed", error)
);
You must add permission rule for Cognito server in the lambda function in order to fetch the user data.
The authentication method will include IAM rule

How to retrieve the logged in Google account on android phones using jquery cordova?

I want to be able to to retrieve the logged in Google account on android phones using jquery cordova
$(function(){
$('#LoginForm').submit(function(){
var loginData = $ ("#LoginForm").serialize();
$.ajax({
type: 'post',
url: "http://admin.payerszone.net/api/Login/s_dynamic",
data: loginData,
crossDomian: true
}).done(function (data) {
console.log(data);
alert(data.cMessage.code)
if(data.cMessage.code == "0"){
window.location.href = "Home.html"
}
else{
window.location.href = "Payment.html"
}
}).error(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText || textStatus);
});
return false;});
})
You can use this cordova plugin to go through the login process:
https://github.com/EddyVerbruggen/cordova-plugin-googleplus
window.plugins.googleplus.login(
{
'scopes': '... ', // optional, space-separated list of scopes, If not included or empty, defaults to `profile` and `email`.
'webClientId': 'client id of the web app/server side', // optional clientId of your Web application from Credentials settings of your project - On Android, this MUST be included to get an idToken. On iOS, it is not required.
'offline': true, // optional, but requires the webClientId - if set to true the plugin will also return a serverAuthCode, which can be used to grant offline access to a non-Google server
},
function (obj) {
alert(JSON.stringify(obj)); // do something useful instead of alerting
},
function (msg) {
alert('error: ' + msg);
}
);
The second parameter is a a callback function when login is successfull. the user info will be passed as a parameter to the callback allong with other information :
obj.email // 'eddyverbruggen#gmail.com'
obj.userId // user id
obj.displayName // 'Eddy Verbruggen'
obj.familyName // 'Verbruggen'
obj.givenName // 'Eddy'
obj.imageUrl // 'http://link-to-my-profilepic.google.com'
obj.idToken // idToken that can be exchanged to verify user identity.
obj.serverAuthCode // Auth code that can be exchanged for an access token and refresh token for offline access
Do follow the installation instructions and get the clientsId from google etc.
Hope it helps

Getting contact.id after saving Cordova contact plugin

I need to get back the contact id after it is saved in order to save it to my online database. However the cordova contact.save() method does not return an id after execution.
Here is my logic:
if ($scope.contact.id === undefined) {
contact.save();
console.log("Contact ID is:", savedContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}
This does not work.
Is there any way to retrieve the id for the contact without having to search the phones contact list using a phone number like this:
if ($scope.contact.id === undefined) {
contact.save();
var savedContact = navigator.contacts.find({ "phoneNumbers[0]": phoneNumbers[0].value });
console.log("Contact ID is:", savedContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}
The above seems like way too much overhead. Not to mention it may not even return the correct contact as a phone number may not be unique.(If someone saves the contact twice with different information)
contact.save() can take two callbacks, success and failure. The success callback should return your newly saved contact (which would include the id.)
if ($scope.contact.id === undefined) {
contact.save(contactSuccess, contactFailure);
}
function contactSuccess(newContact) {
console.log("Contact ID is:", newContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}
function contactError(err) {
//bb10 fires multiple error callbacks with empty errors
if (err) {
console.log(err);
}
}
Since it looks like you are using Angular, check out the ngCordova project. It provides some nice wrappers around some plugins that make everything a bit more readable. Here is the relevant excerpt from their contacts docs:
$cordovaContacts.save($scope.contactForm).then(function(savedContact) {
console.log("Contact ID is:", newContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}, function(err) {
if (err) {
console.log(err);
}
});

Categories

Resources