Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Push server reg android #65

Open
wants to merge 7 commits into
base: push-registration-via-server-android
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions AndroidPushTutorial/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[![Ably](https://s3.amazonaws.com/files.ably.io/logo-with-type.png)](https://www.ably.io)

---

# Android Push Tutorials

This tutorial explains how to use Ably to send Push notification from your private server.

There are some pre-requisites before you can run the app.

1. Register FCM Token from Google Firebase Console
2. Install nodejs to run the local server insider `Server/` folder
3. Setup *.ngrok.io to make the local server accessible via Internet
4. Register an account with Ably and create required App keys.


## Tutorials Setup
1. After the above steps are done, open the `push-demo-server-registration` folder as a project in Android Studio
2. The project might take some time to sync.
3. Replace `google-services.json` into `push-tutorial-one` and `push-demo-server-registration` folder.
4. For this tutorial we have used `io.ably.tutorial.push_tutorial_two` as applicationId for the app respectively. So ensure your FCM Keys have same applicationId. Feel free to modify the tutorials to suit your purpose.
5. Edit `local.properties` file and add the keys, `ably.key` (retrieved from dashboard), `ably.env` (either production or sanbox), `base.url` (pointing to your ngrok.io domain)


109 changes: 109 additions & 0 deletions AndroidPushTutorial/Server/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
var Ably = require('ably')
//replace with actual API key or token
var client = Ably.Realtime(API_KEY)
var express = require('express')
var app = express()

app.get('/auth', (req, res) => {
var tokenParams = {
'clientId': req.query.clientId
};
console.log("Authenticating client:", JSON.stringify(tokenParams));
client.auth.createTokenRequest(tokenParams, function(err, tokenRequest) {
if (err) {
res.status(500).send('Error requesting token: ' + JSON.stringify(err));
} else {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(tokenRequest));
}
});
})

app.get('/register', (req, res) => {

console.log('Registering device')
var deviceId = req.query.deviceId;
var registrationToken = req.query.registrationToken;
var clientId = req.query.clientId;
//var deviceId and deviceToken to be received in the request object
var recipientDetails = {
//It's "fcm" for Android.
transportType: 'fcm',
//replace with actual device token
registrationToken:registrationToken
}

var myDevice = {
id: deviceId,
clientId:clientId,
formFactor: 'phone',
metadata: 'PST',
platform: 'android',
push: {
recipient: recipientDetails
}
}
client.push.admin.deviceRegistrations.save(myDevice, (err, device) => {
if(err){
console.log(err);
} else{
console.log(device);
subscribeDevice(device);
res.setHeader('Content-Type', 'application/json');
res.send(device);
}

})

})

app.get('/push/device', function (req, res) {
var deviceId = req.query.deviceId;

var recipient = {
deviceId: deviceId

};
var notification = {
notification: {
title: 'Hello from Ably!'
}

};
realtime.push.publish(recipient, notification, function(err) {
if (err) {
console.log('Unable to publish push notification; err = ' + err.message);
return;
}
console.log('Push notification published');
res.send("Push Sent");
});
})

function subscribeDevice (device){
var channelSub = {
channel: 'test_push_channel',
deviceId: device.id
}
client.push.admin.channelSubscriptions.save(channelSub, (err, channelSub) => {
if(err){
console.log(err);
} else{
console.log('Device subscribed to push channel with deviceId' + device.id)
}
})
}

app.get('/', (req, res) => {
console.log('Push Notifications tutorial with Ably')
})

app.listen(3000, () => {
console.log('APP LISTENING ON PORT 3000')
})


/*Steps to run this server */
// 1. Download the ably-js 1.1 node library using `npm install ably`
// 2. Replace the 'API_KEY' string with an actual key
// 3. Run the server using `node main.js`
15 changes: 15 additions & 0 deletions AndroidPushTutorial/push-demo-server-registration/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.idea
google-services.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
49 changes: 49 additions & 0 deletions AndroidPushTutorial/push-demo-server-registration/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
applicationId "io.ably.tutorial.push_tutorial_two"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

buildConfigField "String", "ABLY_KEY", "\"${properties.getProperty('ably.key')}\""
buildConfigField "String", "ABLY_ENV", "\"${properties.getProperty('ably.env')}\""
buildConfigField "String", "SERVER_BASE_URL", "\"${properties.getProperty('base.url')}\""
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.code.gson:gson:2.5'

implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-core:16.0.1'

implementation 'io.ably:ably-android:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

/**
* Please ensure to add google-services.json file from your FCM Console.
*/
apply plugin: 'com.google.gms.google-services'
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.ably.tutorial.push_tutorial_two">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service android:name=".receivers.AblyPushMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".receivers.AblyPushRegistrationService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>

</manifest>
Loading