(When I say "App" I am only talking about Android, I'm not gonna even try to deal with Apple)
So I have a website that I'd like to develop an Android app for. All I need it to do is show the website(it'll change some styling if being accessed from the app), which I can do just fine.
I use Intel XDK, which works great. But the notification options it offers seems to be just mass-notification stuff, not individualized.
All I want to do is be able to tell users when they get a notification from my website(like a message from another user).
I've looked all over the place for hours and hours and can't find anything useful. There are a ton of extremely complicated Java codes and tutorials, but I don't even know Java. I'm solely a web developer and all I want is an app that makes it easier for users to check the website.
I'm hoping there is some Java file out there that I can send data to somehow that will allow me to create and delete push notifications on Android systems. Maybe a HTML5 library or JS function, I dunno.
I simply can't seem to implement it myself, and I'm definitely not going to learn an entire dying language just for one basic thing that should be simple to do. Anything you guys can provide would be greatly appreciated. Optimally I would like to get a Java file I can download and put into my app that gives a notification, then I can edit it to say what I need it to or whatever(I also would really like a way to make the notification go away[in case the user sees it on another device before seeing it on the phone] ). I would also need to know how to call onto this Java file, make it check for notifications on the server or whatever.
I know this is all very nooby stuff, but I run an independent website and simply don't have the time to learn all this stuff when my needs are so basic. Thanks in advance.
You can use appMobi for push messaging, see documentation at http://docs.appmobi.com/index.php/push-messages/pushjsapi/. You can setup your appMobi account in the Services tab of the Intel XDK.
//Check if user is registered
var onDeviceReady=function() {
//See if the push user exists already
//You can send any unique user id and password.
AppMobi.notification.checkPushUser(AppMobi.device.uuid, AppMobi.device.uuid);
};
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
//if user is not registered, register them
var isUserAdded = false;
var notificationsRegistered=function(event) {
if(event.success === false) {
if (!isUserAdded) {
isUserAdded= true;
AppMobi.notification.addPushUser(AppMobi.device.uuid,
AppMobi.device.uuid,
'no#email.com');
return;
}
AppMobi.notification.alert("Notifications Failed: " + event.message,
"My Message","OK");
return;
}
var msg = event.message || 'success';
AppMobi.notification.alert("Notifications Enabled: " + msg,
"My Message","OK");
};
document.addEventListener("appMobi.notification.push.enable",
notificationsRegistered,false);
//when push message event is found get notification
var receivedPush = function(){
var myNotifications=AppMobi.notification.getNotificationList();
//It may contain more than one message, so iterate over them
var len=myNotifications.length;
if(len > 0) {
for(i=0; i < len; i++) {
msgObj=AppMobi.notification.getNotificationData(myNotifications[i]);
try{
if(typeof msgObj == "object" && msgObj.id == myNotifications[i]){
AppMobi.notification.alert(msgObj.msg + "\n" + msgObj.data
+ "\n" + msgObj.userkey,"pushMobi Message","OK");
//Always delete messages after they are shown
AppMobi.notification.deletePushNotifications(msgObj.id);
return;
}
AppMobi.notification.alert("Invalid Message Object: " + i,
"My Message","OK");
}catch(e){
AppMobi.notification.alert("Caught Exception For: " + msgObj.id,
"My Message","OK");
AppMobi.notification.deletePushNotifications(msgObj.id);
}
}
}
};
document.addEventListener("appMobi.notification.push.receive", receivedPush, false);
//send a push notification from your website
AppMobi.notification.sendPushNotification(myAppMobiUserID,"new website blog posted!",{});
document.addEventListener("appMobi.notification.push.send",updateNotificationEvent,false);
var updateNotificationEvent=function(event)
{
if(event.success==false)
{
alert("error: " + event.message)
}
else
{
alert("success");
}
}
You can also use Parse.com APIs but I don't believe the subscribe to channel JavaScript API is fully flushed out last I checked, see https://www.parse.com/docs/push_guide#top/JavaScript.
Parse.initialize("YOUR KEY", "HERE");
// Save the current Installation to Parse.
ParseInstallation.getCurrentInstallation().saveInBackground();
You can then send push notifications through the Web Console, or on your website using:
//The following code will push the alert to the "Winterhawks" and "Oil Kings" channels.
Parse.Push.send({
channels: [ "Winterhawks", "Oil Kings" ],
data: {
alert: "The Winterhawks won against the Oil Kings!"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
Subscribe to channels is not yet implemented for JavaScript as far as I know so you'll have to use REST or native APIs.
Related
I have followed the Auto renewing app subscriptions documentation. However the app i am building does not have a server side right now as it stands. I am failing to see if its possible to create the app without the need for the database at all
I have tried simply calling the Purchase.subscribe methods without any saving to a database
public void start() {
Form hi = new Form("Hello World");
//create receiptes store
Purchase.getInAppPurchase().setReceiptStore(createReceieptsStore());
//create a button to purchase the world
Button buyWorld = new Button("Buy World");
buyWorld.addActionListener(e -> {
if (Purchase.getInAppPurchase().isSubscribed(SKU)) {
Dialog.show("Cant Buy It", "You Own It", "OK", null);
} else {
Purchase.getInAppPurchase().subscribe(SKU);
}
});
hi.addComponent(buyWorld);
hi.show();
}
I got an error pertaining to the receipt store fetch and submit methods needing to be implemented
It should be possible to implement subscription without a server but it would be very easy to hack this on any rooted Android device.
I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer
I'm trying to use Azure mobile services to send push notifications. I got it working but currently it sends to all devices that use the application key. I realise that in the gcm.push.send() function I have to give a tag instead of null if i want to send it to individuals or groups.
I want to send it only to the current user. The user who calls the insert. I tried putting in the users gcm registration id but this does not work.
I saw examples of people registering their tags like this (in push->edit script):
exports.register = function (registration, registrationContext, done) {
var userId = registrationContext.user.userId;
registration.tags.push(userId);
done();
};
However im not using authentication so my user variable is undefined. All ive got is a unique identifier in my item table (item.id) and the registration id (item.regid). How can I get my tag working? This is my insert :
function insert(item, user, request) {
console.log("Registration ID -> " + item.regid);
var payload = {
"data": {
"message": "notification added"
}
};
request.execute({
success: function() {
// If the insert succeeds, send a notification.
push.gcm.send(item.regid, payload, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
request.respond(500, { error: pushResponse });
}
});
},
error: function(err) {
console.log("request.execute error", err)
request.respond();
}
});
}
Notification Hubs does not have the ability to send to a specific device right now.
The mechanism for simulate this is through the registration process and tags. Use the Notification Hubs API directly. When you register a device, register to listen with a tag that is appropriate to the device or user. For example, register to listen to tags USER-userid and DEVICE-deviceid.
Then, when you want to send to a specific device, send to DEVICE-deviceid and if you want to send to all devices that are registered to a specific user, you can send to USER-userid; obviously, replace the userid and deviceid with the appropriate values.
You can find out more about tags here: https://msdn.microsoft.com/library/azure/dn530749.aspx
If you want to send notification to specific user you must register them with unique tag or unique identifier as Adrian hall in previous answer described,I agree with him.As unique identifier in Android you can use DeviceId and in Ios identifierForVendor they are unique and they never change.
I have a web application which serves as the Admin Panel. It has a live chat option which connects with writers(employees) on the other end. The web application uses the following PHP code to check for online writers.
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while ($q<5){
sleep(3);
$wresult = $db->query("SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if ($wresult->num_rows){ break; }
++$q;
}
if ($wresult->num_rows){
while ($row = $wresult->fetch_object()){ $writers[] = $row; }
$wresult->free();
}
echo json_encode(
array(
"writers" => $writers,
"now" => time()
)
);
On the application the following javascript code handles the PHP response and calls ajax again to complete the loop.
function UpdateCHAT(){
$.ajax({
type: "POST",
url: "liveserver.php",
data: {update:"1",timestamp:lastime},
success:
function(data1){
if (data1 == null){
$(".onlinechat i").removeClass("icon-white");
}else{
lastime = user_signin = Number(data1.now);
if (!data1.writers.length){
$(".onlinechat i").removeClass("icon-white");
}else{
$(".onlinechat i").removeClass("icon-white");
$.each(data1.writers,function(j) {
$("#writer_"+data1.writers[j].writer_alias).find("i").addClass("icon-white");
});
}
}
},
dataType: "json",
timeout: 60000,
complete:
function(){
UpdateCHAT();
}
}
);
}
Everything is working just fine except the fact that I cannot think of a way to know for offline writers since the PHP code is designed to check for the online writers, but this means if a writer is online once, he will remain online (on the application) until the PHP code dies and return empty writers.
Hope I am able to explain my point. This question is more to do with idea rather than piece of code. Any input is appreciated.
Thanks.
Make the PHP code always return after some time (like 2 minutes) with an empty result set (ie. no new chat lines).
JS will then do a new request immediately. If it doesn't, well, then the user is offline. Keep a last_request timestamp, if it's older than 2+e minutes the user is offline.
You could try to detect when the connection closes in PHP. Set ignore_user_abort(true) so you are in control of when your script dies. Then use connection_aborted() to check if the client closed. If he did you know he left.
A potential problem occurs if the user has two windows open: a close on one doesn't mean he left, but this may turn out to be acceptable; the user will blip for just a while.
Another solution is to use a separate ping request that just tells you "yep, I'm still here". If you haven't gotten one of those in a while the user is probably offline.
I need to upload multiple files from jsp. I am using $ajaxFileUPload.js to take the file to server side. I am doing my file size validation in server side for each file. I need a message on validating the file, where i face a problem. I am not able to show that message. Could someone help me in this please?
I have not used the plugin but what I have done previously in similar situation is send different markers back to the client side like for an upload the exceeds the file limit size, you can start the response back with something like 'ERROR:' and then look for this marker in the function getting the response back and then branch to a different logic. You obviously have to parse the response and look for the marker.
Looking quickly at the plugin in Github, it looks like the usage is
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
So what I think you can do is in the onComplete function something like
if (response.search("ERROR:") != -1){
//error condition
//add your msg for the front end here
} else {
//non error condition, continue with your regular flow
}
Does this make sense and relate to what you are trying to do?