Android AWS Appsync subscription does not fire events - android

AWS Appsync subscription does not fire events.I did not receive events from the socket. The watcher seems to work fine because if i pass a wrong token (for test) it fire onFailure event.
What i have done is:
Update my project gradle:
classpath 'com.amazonaws:aws-android-sdk-appsync-gradle-plugin:2.7.+'
Update my app gradle:
apply plugin: 'com.amazonaws.appsync'
and dependencies:
implementation 'com.amazonaws:aws-android-sdk-appsync:2.7.+'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
Put these files inside app/src/main/graphql
queries.graphql
subscription subscribeToNotify($userId: ID!, $deviceId: ID!){ subscribeToNotify(userId: $userId, deviceId: $deviceId){ userId deviceId body } }
schema.json (downloaded from console)
My configuration json is:
{
"UserAgent": "aws-amplify-cli/0.1.0",
"Version": "1.0",
"IdentityManager": {
"Default": {}
},
"AppSync": {
"Default": {
"ApiUrl": "https://XXX",
"Region": "eu-west-1",
"AuthMode": "OPENID_CONNECT"
},
"Demo": {
"ApiUrl": "https://XXX",
"Region": "eu-west-2",
"AuthMode": "OPENID_CONNECT"
}
}
}
Manifest:
`
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<service android:name="org.eclipse.paho.android.service.MqttService" />
My activity:
private lateinit var appSyncClient : AWSAppSyncClient
private lateinit var watcher: AppSyncSubscriptionCall<SubscribeToNotifySubscription.Data>
private var callback:AppSyncSubscriptionCall.Callback<SubscribeToNotifySubscription.Data> = object : AppSyncSubscriptionCall.Callback<SubscribeToNotifySubscription.Data> {
override fun onResponse(response: Response<SubscribeToNotifySubscription.Data>) {
runOnUiThread {
Timber.i("Subcription onResponse invoked $response")
Timber.e("Subcription onResponse invoked $response")
Timber.d("Subcription onResponse invoked $response")
}
}
override fun onCompleted() {
Timber.i("Subcription onCompleted invoked")
}
override fun onFailure(e: ApolloException) {
Timber.e("Subcription ERROR $e")
}
}
override fun subscribeToNotification(userID: String, deviceID: String, clearToken:String) {
try{
Timber.d("subscribeToNotification INVOKED")
val clientConfiguration : AWSConfiguration = AWSConfiguration(this)
appSyncClient = AWSAppSyncClient.builder().context(applicationContext).awsConfiguration(clientConfiguration).oidcAuthProvider { clearToken }.build()
//subscribeToNotify
var app_event_subscription = SubscribeToNotifySubscription.builder().deviceId(deviceID).userId(userID!!).build()
watcher = appSyncClient.subscribe(app_event_subscription)
watcher.execute(callback)
}catch (ex:Exception){
Timber.e("EXCEPTION CONNETING "+ex.message)
}
}
When the backend send me a notification nothing appear in log console but i can read that the subsription is done:
2019-04-25 10:49:28.456 12082-12317/infinite_software.intelligence_center.intelligencecenter D/RealSubscriptionManager: Subscription Infrastructure: Adding subscription object com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject#4d109b1 to topic 156616541434/2b4hzivvqvdwzmcy4wibyy2sku/subscribeToNotify/85582f91c6e6a66749f4e0e9c4d74ea7abef52b2e4c0242517e5236d4d51be60. Total subscription objects: 1
and the scheduler that works (every X seconds):
2019-04-25 10:50:59.996
12082-12082/infinite_software.intelligence_center.intelligencecenter
D/AlarmPingSender: Sending Ping at:1556185859996 2019-04-25
10:51:00.006
12082-12082/infinite_software.intelligence_center.intelligencecenter
D/AlarmPingSender: Schedule next alarm at 1556185890006 2019-04-25
10:51:00.006
12082-12082/infinite_software.intelligence_center.intelligencecenter
D/AlarmPingSender: Alarm scheule using setExactAndAllowWhileIdle,
next: 30000 2019-04-25 10:51:00.033
12082-12350/infinite_software.intelligence_center.intelligencecenter
D/AlarmPingSender: Success. Release
lock(MqttService.client.dcuju2iftbdgplcvdamtlghzuu):1556185860033
I missing something ?

Related

Pushwoosh and Android Phonegap App not communicating

The Problem
Okay so I have a Phonegap (2.3.0) android application with Pushwoosh to manage the push notifications. I followed the instructions, and got an app with only a few wording errors working. The app itself seems to run perfectly fine, however it doesn't seem like Pushwoosh is pushing anything to GCM (Google Cloud Messanger), which it turn isn't pushing anything to the app. Now that is what I think is wrong, however this is my first time using GCM and Pushwoosh.
On the Pushwoosh console page it shows each "push" as completed with no errors, but then on my GCM console it doesn't show any requests, nor do any notification pop up on my phone.
I have the GCM API key (server key) in my XML and my Pushwoosh is the correct XXXXX-XXXXX key. Here is my code to better outline how my code is setup (and maybe someone can see what I'm missing).
The Code
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--library-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!--
Creates a custom permission so only this app can receive its messages.
NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
where PACKAGE is the application's package name.
-->
<permission
android:name="com.springmobile.employee.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission
android:name="com.springmobile.employee.permission.C2D_MESSAGE"/>
<!-- This app has permission to register and receive data message. -->
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE"/>
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:allowBackup="true">
<!--
Service for sending location updates
-->
<service android:name="com.arellomobile.android.push.GeoLocationService"/>
<intent-filter>
<action android:name="com.springmobile.employee.MESSAGE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<activity android:name="com.arellomobile.android.push.PushWebview"/>
<activity android:name="com.arellomobile.android.push.MessageActivity"/>
<activity android:name="com.arellomobile.android.push.PushHandlerActivity"/>
<!--
BroadcastReceiver that will receive intents from GCM
services and handle them to the custom IntentService.
The com.google.android.c2dm.permission.SEND permission is necessary
so only GCM services can send data messages for the app.
-->
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="com.springmobile.employee"/>
</intent-filter>
</receiver>
<!--
Application-specific subclass of PushGCMIntentService that will
handle received messages.
-->
<service android:name="com.arellomobile.android.push.PushGCMIntentService"/>
<activity android:name="org.apache.cordova.example.cordovaExample" android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Here is my Phonegap plugin config.XML
<plugins>
<plugin name="PushNotification" value="com.pushwoosh.plugin.pushnotifications.PushNotifications" onload="true"/>
</plugins>
Here is the JS for my Phonegap page to initialize and listen for the Pushwoosh Notification.
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
pushNotification.onDeviceReady();
pushNotification.registerDevice({ projectid: "I_HAVE_MY_PROJECT_ID_HERE", appid : "THIS_IS_MY_PUSHWOOSH_ID" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
}
);
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
function init() {
document.addEventListener("deviceready", initPushwoosh, true);
//rest of the code
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
console.warn('user data: ' + JSON.stringify(userData));
navigator.notification.alert(title);
});
}
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
pushNotification.onDeviceReady();
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
pushNotification.stopGeoPushes();
});
}
function registerPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
//projectid: "GOOGLE_PROJECT_ID", appid : "PUSHWOOSH_APP_ID"
pushNotification.registerDevice({ projectid: "1039894503284", appid : "EE861-B95A3" },
function(token) {
alert(token);
onPushwooshInitialized(token);
},
function(status) {
alert("failed to register: " + status);
console.warn(JSON.stringify(['failed to register ', status]));
});
}
function unregisterPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
pushNotification.unregisterDevice(function(token) {
alert("unregistered, old token " + token);
},
function(status) {
alert("failed to unregister: " + status);
console.warn(JSON.stringify(['failed to unregister ', status]));
});
}
//set the settings for Pushwoosh or set tags, this must be called only after successful registration
function onPushwooshInitialized(pushToken)
{
//output the token to the console
console.warn('push token: ' + pushToken);
var pushNotification = window.plugins.pushNotification;
//set multi notificaiton mode
//pushNotification.setMultiNotificationMode();
//set single notification mode
//pushNotification.setSingleNotificationMode();
//disable sound and vibration
//pushNotification.setSoundType(1);
//pushNotification.setVibrateType(1);
pushNotification.setLightScreenOnNotification(false);
//goal with count
//pushNotification.sendGoalAchieved({goal:'purchase', count:3});
//goal with no count
//pushNotification.sendGoalAchieved({goal:'registration'});
//setting list tags
//pushNotification.setTags({"MyTag":["hello", "world"]});
//settings tags
pushNotification.setTags({deviceName:"hello", deviceId:10},
function(status) {
console.warn('setTags success');
},
function(status) {
console.warn('setTags failed');
});
function geolocationSuccess(position) {
pushNotification.sendLocation({lat:position.coords.latitude, lon:position.coords.longitude},
function(status) {
console.warn('sendLocation success');
},
function(status) {
console.warn('sendLocation failed');
});
};
// onError Callback receives a PositionError object
//
function geolocationError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function getCurrentPosition() {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
}
//greedy method to get user position every 3 second. works well for demo.
// setInterval(getCurrentPosition, 3000);
//this method just gives the position once
// navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
//this method should track the user position as per Phonegap docs.
// navigator.geolocation.watchPosition(geolocationSuccess, geolocationError, { maximumAge: 3000, enableHighAccuracy: true });
//Pushwoosh Android specific method that cares for the battery
pushNotification.startGeoPushes();
}
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
initPushwoosh();
app.receivedEvent('deviceready');
//optional: create local notification alert
//var pushNotification = window.plugins.pushNotification;
//pushNotification.clearLocalNotification();
//pushNotification.createLocalNotification({"msg":"message", "seconds":30, "userData":"optional"});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
Here is the PushWoosh.js code
(function(cordova) {
function PushNotification() {}
// Call this to register for push notifications and retreive a deviceToken
PushNotification.prototype.registerDevice = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
};
// Call this to set tags for the device
PushNotification.prototype.setTags = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
};
// Call this to send geo location for the device
PushNotification.prototype.sendLocation = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
};
//Android Only----
PushNotification.prototype.unregisterDevice = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
};
//config params: {msg:"message", seconds:30, userData:"optional"}
PushNotification.prototype.createLocalNotification = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "createLocalNotification", config ? [config] : []);
};
PushNotification.prototype.clearLocalNotification = function() {
cordova.exec(null, null, "PushNotification", "clearLocalNotification", []);
};
//advanced background task to track device position and not drain the battery
PushNotification.prototype.startGeoPushes = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
};
PushNotification.prototype.stopGeoPushes = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
};
//sets multi notification mode on
PushNotification.prototype.setMultiNotificationMode = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "setMultiNotificationMode", []);
};
//sets single notification mode
PushNotification.prototype.setSingleNotificationMode = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "setSingleNotificationMode", []);
};
//type: 0 default, 1 no sound, 2 always
PushNotification.prototype.setSoundType = function(type, success, fail) {
cordova.exec(success, fail, "PushNotification", "setSoundType", [type]);
};
//type: 0 default, 1 no vibration, 2 always
PushNotification.prototype.setVibrateType = function(type, success, fail) {
cordova.exec(success, fail, "PushNotification", "setVibrateType", [type]);
};
PushNotification.prototype.setLightScreenOnNotification = function(on, success, fail) {
cordova.exec(success, fail, "PushNotification", "setLightScreenOnNotification", [on]);
};
//set to enable led blinking when notification arrives and display is off
PushNotification.prototype.setEnableLED = function(on, success, fail) {
cordova.exec(success, fail, "PushNotification", "setEnableLED", [on]);
};
//{goal:'name', count:3} (count is optional)
PushNotification.prototype.sendGoalAchieved = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "sendGoalAchieved", config ? [config] : []);
};
//Android End----
//iOS only----
PushNotification.prototype.onDeviceReady = function() {
cordova.exec(null, null, "PushNotification", "onDeviceReady", []);
};
// Call this to get a detailed status of remoteNotifications
PushNotification.prototype.getRemoteNotificationStatus = function(callback) {
cordova.exec(callback, callback, "PushNotification", "getRemoteNotificationStatus", []);
};
// Call this to set the application icon badge
PushNotification.prototype.setApplicationIconBadgeNumber = function(badge, callback) {
cordova.exec(callback, callback, "PushNotification", "setApplicationIconBadgeNumber", [{badge: badge}]);
};
// Call this to clear all notifications from the notification center
PushNotification.prototype.cancelAllLocalNotifications = function(callback) {
cordova.exec(callback, callback, "PushNotification", "cancelAllLocalNotifications", []);
};
//iOS End----
// Event spawned when a notification is received while the application is active
PushNotification.prototype.notificationCallback = function(notification) {
var ev = document.createEvent('HTMLEvents');
ev.notification = notification;
ev.initEvent('push-notification', true, true, arguments);
document.dispatchEvent(ev);
};
cordova.addConstructor(function() {
if(!window.plugins) window.plugins = {};
window.plugins.pushNotification = new PushNotification();
});
})(window.cordova || window.Cordova || window.PhoneGap);
Screenshots of GCM, Pushwoosh and Eclipse
Sorry this is lengthy but I want to make sure I have everything here. Also not enough rep to post images so links below.
GCM API server key, Pushwoosh Control Panel, and Eclipse setup
Thanks!
lets check your configuration and setup is proper for push woosh notification .Other Push notification service is also work in phone-gap you can check it out.You can find phone gap code(zip),proper documentation for configuration and setup and how to use their API using Java script
The Pushwoosh version is very important while configuring it with a phonegap application, so you need to be sure that your Pushwoosh script is compatible with Phonegap 2.3.0. If the Pushwoosh script is not correct, it will not work with your Phonegap version and I think that they only support the latest Phonegap available right now.
The GCM API key must be for Android Application, not server
I had this issue because my bundle id wasn't correct.
Be sure that your app name and the bundle id are the same in xcode and your iOS app Indentifier in https://developer.apple.com/account/ios/identifiers.

Dropbox integration using oAuth2 Url in React Native Android is not working with handleOpenUrl

I have successfully integrated dropbox oAuth2 and Writing files to dropbox in react native for iOS. Same code is not working for Android.
I am using oAuth Url and handleOpenUrl in react native to read the incoming links in Android.
It opens the Dropbox website with the OAuthUrl and authorizes the user. In Dropbox website when it asks permission to access files and folders, when we tap on "Allow" it doesn't open my app.
So the control is not passed back and it doesn't call handleOpenUrl method. Not sure what I am missing.
I also tried with below method:
Linking.getInitialURL().then((url) => {
if (url) {
console.log('Initial url is: ' + url);
this.navigate(url);
}
But this gives url comes as undefined.
In AndroidManifest.XML file I added the intent filter and permissions :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https"
android:host="www.dropbox.com" />
<data android:scheme="https"
android:host="www.dropbox.com/oauth2/authorize" />
<!-- Oauth2 redirect url set when dropbox app is created -->
<data android:scheme="com.companyname.appname.oauth"
android:host="oauthredirect" />
</intent-filter>
In Activity tag added android:launchMode="singleTask".
Below is the code snippet of React Native code :
export class DropboxAuthorize implements Authorize {
constructor() {
this._handleOpenURL = this._handleOpenURL.bind(this);
}
// Authorize with Dropbox. Uses the device's browser to work through the Dropbox
// OAuth 2 process, eventually recording a token and account ID if successful.
public authorize(): Promise<void> {
console.log("Authorization starting...");
// Generate a random string for Dropbox's state param.
// This helps us be sure a deep link into the app is indeed related to the request
// we made to Dropbox.
const stateValue = Math.random().toString();
console.log("authorize stateValue",stateValue);
// Open the Dropbox authorization page in the device browser
return Linking.openURL(
[
'https://www.dropbox.com/oauth2/authorize',
"?response_type=token",
`&client_id=${DROPBOX.OAUTH_CLIENT_ID}`,
`&redirect_uri=${DROPBOX.OAUTH_REDIRECT_URI}`,
`&state=${stateValue}`
].join("")
)
.catch(err =>
console.error(
"An error occurred trying to open the browser to authorize with Dropbox:",
err
)
)
.then(() => {
return new Promise((resolve, reject) => {
const handleOpenURL = (event: { url: string }) => {
console.log("event", event);
this._handleOpenURL(event, stateValue)
.then(() => {
resolve();
})
.catch(reason => {
reject(reason);
})
.then(() => {
// "Finally" block
// Remove deep link event listener
Linking.removeEventListener("url", handleOpenURL);
return;
});
};
console.log("Hi there");
// Add deep link event listener to catch when Dropbox sends the user back to the app.
Linking.addEventListener("url", handleOpenURL);
});
});
}
private _handleOpenURL(
event: { url: string },
stateValue: string
): Promise<void> {
console.log("Deep link event!", event);
console.log("State Value",stateValue);
const queryStringResult = event.url.match(/\#(.*)/);
if (queryStringResult === null || queryStringResult.length < 2) {
return Promise.reject(
"Did not receive a query string as part of this deep link!"
);
}
const [, queryString] = queryStringResult;
const parsedQueryString = shittyQs(queryString);
console.log ("parsedQueryString",parsedQueryString);
if (parsedQueryString.error) {
// There was an error!
const errorCode = parsedQueryString.error;
const errorDescription = parsedQueryString.error_description;
console.error("Dropbox OAuth error! code:", errorCode);
console.error("Error description:", errorDescription);
return Promise.reject(
`Could not authorize with Dropbox. Code: ${errorCode}`
);
}
if (parsedQueryString.state){
if (stateValue !== parsedQueryString.state) {
// This value must match! This is a security feature of Dropbox's OAuth impl
return Promise.reject("State parameter DID NOT MATCH!");
}
}
// Otherwise: not an error!
const accessToken = parsedQueryString.access_token;
const accountId = parsedQueryString.account_id;
// Persist accessToken and accountId
return AsyncStorage.setItem(DROPBOX.ACCESS_TOKEN_STORAGE_KEY, accessToken)
.then(() => {
/* return AsyncStorage.setItem(DROPBOX.ACCOUNT_ID_STORAGE_KEY, accountId);
})
.then(() => { */
console.log(
"Dropbox OAuth authorization success! Access Token:",
accessToken
);
/* console.log(
"Dropbox OAuth authorization success! Account ID:",
accountId
); */
return;
});
}
Let me know if any alternative method is available to read the incoming links.

Open local file in pdf.js android webview (“file” is not supported error)

I'm trying to follow the answer stated here. Based on the comments, loading a local file using pdf.js in android webview should work but I am getting the below error:
I/chromium: [INFO:CONSOLE(18556)] "Fetch API cannot load file:///android_asset/www/pdfjs/web/tracemonkey.pdf. URL scheme "file" is not supported.", source: file:///android_asset/www/pdfjs/build/pdf.js (18556)
I/chromium: [INFO:CONSOLE(13127)] "Uncaught (in promise) DataCloneError: Failed to execute 'postMessage' on 'Worker': TypeError: Failed to fetch could not be cloned.", source: file:///android_asset/www/pdfjs/build/pdf.js (13127)
[INFO:CONSOLE(985)] "Uncaught (in promise) Error: An error occurred while loading the PDF.", source: file:///android_asset/www/pdfjs/web/viewer.js (985)
Here is my code:
class PDFViewerLocalActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.pdfviewer_layout)
val webView = findViewById(R.id.pdfViewer) as WebView
webView.settings.javaScriptEnabled = true
webView.settings.allowFileAccessFromFileURLs = true
webView.settings.allowUniversalAccessFromFileURLs = true
webView.settings.builtInZoomControls = true
webView.webChromeClient = WebChromeClient()
webView.loadUrl("file:///android_asset/www/pdfjs/web/viewer.html?file=tracemonkey.pdf")
}
}
Okay, this was a dumb question. I already put the following permissions in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
But forgot that for API 23 and above you have to request permission at run time. So, just added the code to request permissions and it worked.
#TargetApi(23)
fun askPermissions() {
val permissions = arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE")
val requestCode = 200
requestPermissions(permissions, requestCode)
}

open failed: EACCES (Permission denied) in ionic -2

I was using cordova-plugin-file-transfer and cordova-plugin-file-chooser on Ionic mobile application to upload some files to Android device which can open with native applications like pdf, word, excel..etc
It is now throwing "exception":"/storage/emulated/0/Download/pdf-test.pdf: open failed: EACCES (Permission denied)"}".
openFile() {
console.log("openFile");
this.fileChooser.open()
.then(uri => {
console.log(uri)
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'files',
fileName: 'name.doc',
params: { resume: uri},
chunkedMode: false,
headers: {
'token': this.token,
'sid': this.sid,
'user': this.user,
'to': this.to,
'node': this.node,
'type': 'doc',
'cap': this.cap
}
}
console.log("Headers" + JSON.stringify(options));
fileTransfer.upload(uri,this.apiurl, options)
.then((data) => {
// success
console.log("Response data ->>>>>>> :- " + JSON.stringify(data));
alert("success" + JSON.stringify(data));
}, (err) => {
// error
console.log("Error data ->>>>>>> :- " + JSON.stringify(err));
alert("error" + JSON.stringify(err));
});
})
.catch(e => console.log(e));
}
I also added permission on AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Android Permissions
This plugin is designed for supporting Android new permissions checking mechanism.
Since Android 6.0, the Android permissions checking mechanism has been changed. In the past, the permissions were granted by users when they decide to install the app. Now, the permissions should be granted by a user when he/she is using the app.
For old Android plugins you (developers) are using may not support this new mechanism or already stop updating. So either to find a new plugin to solving this problem, nor trying to add the mechanism in the old plugin. If you don't want to do those, you can try this plugin.
https://ionicframework.com/docs/native/android-permissions/
filePermission() {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE).then(
result => console.log('Has permission?', result.hasPermission),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE)
);
}

Push not working with Parse-server hosted on Localhost/amazon beanstalk

In my AfterSave I fire a push and I can see Success statements being printed in CloudCode but nothing being received on my IOS or Android device.
Here is the Cloudcode:
function senderPush(instalationId, receiverName, receiverNumber, message, status ) {
var query = new Parse.Query(Parse.Installation);
query.equalTo("installationId", instalationId);
Push.send({
where: query,
data: {
header: "Status : " + status ,
...
badge: "Increment",
message : message,
status : status,
}
},{
success: function() {
console.log("notification sent");
},
error: function(error) {
console.log("Error sending senderPush: " + error);
},
useMasterKey: true
});
}
Here is AndroidManifest.xml :
<receiver android:name="com.Myapplication.receiver.StatusReceiver" android:exported="false">
<intent-filter>
<action android:name="com.Myapplication.receiver.UPDATE_STATUS" />
</intent-filter>
</receiver>
<service
android:name="com.Myapplication.util.VoiceCommandService"
android:exported="false">
</service>
<meta-data android:name="com.parse.push.gcm_sender_id" android:value="id:XXXXXXXX" />'
Here is my Application.Java :
Parse.addParseNetworkInterceptor(new ParseLogInterceptor());
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(APPLICATION_ID)
.server(BRConstants.MY_IP_ADDRESS_SERVER).build()
);
Everything else is working fine. But push doesn't seem to work. No Errors, nothing. When I send data from Android, I am getting this message in Console which has request but no response :
GCM request and response {"request":{"params":
{"priority":"normal","data":{"time":"2016-07-
18T19:50:01.949Z","push_id":"2SxLKSeThF","data":"{\"header\":\"Status :
Cancelled\",\"alertMessage\":\".....
MYDATA.......\":\"Cancelled\"}"}}}}
Not sure what am I missing here.
You get 2 keys from GCM.
One for the Android device and another is for the server. In the parse, you need to put the server key.

Resources