I am working on Firebase FireStore and Firebase real time database apps,
how can I set an alarm (based on a value set by the user) on android using firebase cloud functions?
There is currently no one-time scheduling functionality in Cloud Functions. You will have to provide your own scheduling mechanism, and that could trigger an HTTP function that deals with Firestore or Realtime Database.
You can use Javacript native function in Firebasefunctions -
setTimeOut()
setInterval()
for triggering some events .
Working for me.My use case is to trigger some API after each 5mins.
Sample Code -
exports.process_sms = functions.https.onRequest((req, res) => {
admin.database().ref(FIREBASE_DB + '/sms_new').once('value').then(function(users) {
let sms_array = [];
users.forEach(function(user) {
user.forEach(function(sms) {
if (sms.val().status == 0) {
sms_array.push(sms);
}
});
});
let i = 0;
let interval = setInterval(function() {
// do your work ... and it gets repeated after 2 sec
}, 2000);
res.status(200).send("Sms processing Done");
});
});
Related
I have developed screen casting app. I am making connection using twilio but I want to share touch events from receiver(participant) to sender(host) as a live data. Is there any possible solution to simplify this?
If you are using Twilio Video for this connection then you can use the DataTrack API to send arbitrary data over your connection.
You can create a LocalDataTrack object:
const { LocalDataTrack } = require(`twilio-video`);
const dataTrack = new LocalDataTrack();
Connect it to a room, either by sending it as part of the tracks option when connecting, or by publishing it to the room after a connection has been made.
const { connect } = require('twilio-video');
const room = await connect('$TOKEN', {
name: 'my-chat-room',
tracks: [dataTrack]
});
You can send a message down the data track once it is published:
dataTrack.send(message)
And you can receive data track messages by subscribing to the track and listening for the message event:
participant.on('trackSubscribed', track => {
console.log(`Participant "${participant.identity}" added ${track.kind} Track ${track.sid}`);
if (track.kind === 'data') {
track.on('message', data => {
console.log(data);
});
}
});
See the documentation for more detail.
I am making an application using flutter and firebase. I need to get active users from firebase.
I am trying by creating a boolean field in firebase collection with name isActive = false and initiate a function with name _checkInternetConnectivity(); in this function I set when the internet connection is available update value of isActive = true in firebase and when there is no internet connection update value isActive = false so far my code is working perfectly but problem is that when internet connection is available it set the value of isActive = true but when there is no internet connection it unable to update the value isActive = false.
code is here:
void initState() {
super.initState();
_checkInternetConnectivity();
}
_checkInternetConnectivity() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
'isActive': true,
});
print('done mobile');
} else if (connectivityResult == ConnectivityResult.wifi) {
_addData.doc(user.uid).update({
'isActive': true,
});
print('done wifi');
} else if (connectivityResult == ConnectivityResult.none) {
FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
'isActive': false,
});
print('done none');
}
}
}
so, how I can improve this code or any other way by which I can get active users from firebase with flutter. Regards
OnDisconnect
The OnDisconnect class is used to manage operations that will be run on the server when this client disconnects. It can be used to add or remove data based on a client's connection status. It is very useful in applications looking for 'presence' functionality.
Instances of this class are obtained by calling onDisconnect on a Firebase Database ref.
Your solution is here
You can create a field like lastActiveTimestamp and update it every time an user opens the app. Then you can filter users by the last time they use the app.
How do I do this? I used the code below but it is not working. I still receive notification when I update my Database
exports.sendNewPostNotif = functions.database.ref('/News/{ID}').onWrite(event => {
const announce_data = event.data.val();
const announce_data_type = announce_data.categ_post;
const announce_data_title = announce_data.title_post;
const announce_data_uid = announce_data.uid; id
const announce_post_key = announce_data.postkey;
if(!event.data.val()) {
return console.log('No data');
}
if(event.data.previous.exist()) {
return;
}
Whenever I send a new content, it'll go through the onWrite event then send the notification. Mmy current issue is whenever I edit the post, it'll send a notification which I do not require. I tried the above and it works as I receive no notification when I update the news content BUT I don't receive a notification when I create a new content.
If you only want your function to run when the node is created, and not when it is updated or deleted, you can use the onCreate trigger:
exports.sendNewPostNotif = functions.database.ref('/News/{ID}').onCreate(event => {
See the Firebase documentation on database trigger types and the blog post where these are introduced.
I'm using Firebase Android SDK and became interested in sending synchronous request instead of asynchronous. According to the documentation, in any request callbacks are presented. But what about the synchronicity?
Thanks!
There is no way to synchronously load data from the Firebase Database.
While it is common for developers new to Firebase to wish for a synchronous method, it simply doesn't fit with Firebase's data synchronization model. Also see my answer here: Setting Singleton property value in Firebase Listener
It is not possible to load data synchronously with the official SDK. However, you can access all the data in firebase using the REST API. This would allow you to make synchronous calls. As mentioned about, Firebase is a realtime database and you will be missing the feature of updates when your data changes.
I made a simple class to call tasks synchronously in Android.
Note that this is similar to Javascript's async await function.
Check my gist.
TasksManager.class
public class TasksManager {
...
public ExecutorService getExecutor() {
if (mDefaultExecutor == null || mDefaultExecutor.isShutdown() || mDefaultExecutor.isTerminated()) {
// Create a new ThreadPoolExecutor with 2 threads for each processor on the
// device and a 60 second keep-alive time.
int numCores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
numCores * 2,
numCores * 2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
mDefaultExecutor = executor;
}
return mDefaultExecutor;
}
public static <TResult> Task<TResult> call(#NonNull Callable<TResult> callable) {
return Tasks.call(getInstance().getExecutor(), callable);
}
}
Here's a sample code to use it.
TasksManager.call(() -> {
Tasks.await(AuthManager.signInAnonymously());
// You can use multiple Tasks.await method here.
// Tasks.await(getUserTask());
// Tasks.await(getProfileTask());
// Tasks.await(moreAwesomeTask());
// ...
startMainActivity();
return null;
}).addOnFailureListener(e -> {
Log.w(TAG, "signInAnonymously:ERROR", e);
});
While it is not possible to load data from the FirebaseDatabase in a synchronous way, it is possible to wait for the load to finish synchronously.
You can wrap your value listener in a CountDownLatch and count down,
once the onDataChange or onCancelled implementation is called.
This is actually what the Tasks api is doing internally if you call Tasks.await(someTask).
You should use the value listener for single event listening, because in this case I assume you don't want continued updates. And use a proper timeout for the CountDownLatch, since Firebase won't timeout, ever.
reference.addListenerForSingleValueEvent(...);
You also have to take into account, that if you have the FirebaseDatabase
cache enabled, the first result might not be the actual value on the
server.
I have to add: While this might work, it is against the idea how firebase is designed and supposed to be used, as Frank already said.
If you are using Kotlin, add an extension function:
private suspend fun <TResult> Task<TResult>.await(): TResult? {
return try {
Tasks.await(this)
} catch (e: Exception) {
null
}
}
Now you can do
val snapshot = fireStore.collection(USER_ROOT_PATH).document(documentPath)?.get()?.await()
I have created a REST service using Node.js and MongoDB for using in one of my Android app.
The get methods is working as expected when called from Android App.
I am trying to build a JSON object from Android App with necessary details and post to the service.I am unable to post to my collections. Below is the code snippet I have used in my Node.js
app.post('/accounts/put/:uObject', function(req, res, next) {
var username=uObject.name;
db.collection('test').insert({"username":username},function(err,docs){if(err){
res.send("There was some problem during insertions of linkes");
}
else{
res.send("Fail");
} });
});
What Am I doing wrong in this? I am getting the object as parameter and getting the values inside the function and passing to the insert.
To get the parameter from the route you need to use req.params, in your case req.params.uObject. Also common practice in JavaScript is to return early upon a condition being met.
app.post('/accounts/put/:uObject', function(req, res, next) {
var username = req.params.uObject;
db.collection('test').insert({
"username": username
}, function(err, docs) {
if (err) {
return res.send("There was some problem during insertions of linkes");
}
res.send("Fail");
});
});