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.
Related
I am making a chat feature in the android app using Conversations SDK. The reachability is enabled from the backend side. I try to get live updates of the online/offline status of all the users. But the flow doesn't come in onUserUpdated() method of ConversationsClientListener. Below is the code I have implemented to get the live status updates.
fun getUserStatus(): Flow<User> = callbackFlow {
val client = instantMessageRepository.getConversationsClient()
val listener = createClientListener (
onUserUpdated = { user, updateReason ->
user.let { trySend(it).isSuccess }
}
)
client.addListener(listener)
awaitClose { client.removeListener(listener) }
}
And I am getting it as live data as follows:
val userStatus = chatService.getUserStatus()
.asLiveData(viewModelScope.coroutineContext)
And listening it in my activity as follows:
mViewModel.userStatus.observe(viewLifecycleOwner) {
Log.d(TAG, "onViewCreated: ${it.isOnline}")
}
Is this the right way to get live user status updates online/offline? Or do I need some corrections or change the way I'm trying to implement it?
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 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");
});
});
I am using react-native-sync-adapter in my react-native Android app. The sync service triggers a function at every fixed interval in the background.
I use the following function to check for internet availability in the trigger.
export function isNetworkConnected() {
return NetInfo.fetch().then(reachability => {
if (reachability === 'unknown') {
return new Promise(resolve => {
const handleFirstConnectivityChangeIOS = isConnected => {
NetInfo.isConnected.removeEventListener('change', handleFirstConnectivityChangeIOS);
resolve(isConnected);
};
NetInfo.isConnected.addEventListener('change', handleFirstConnectivityChangeIOS);
});
}
reachability = reachability.toLowerCase();
return (reachability !== 'none' && reachability !== 'unknown');
});
}
On a real device, when I disable WiFi, open the app (the app also calls the same method on launch and sets the state of connectivity to false), push the app to the background again and enable WiFi, isNetworkConnected() returns false always.
What can be possibly wrong?
PS: react-native version 0.42.3
I am attempting to create a real-time communication capability for a Phonegap/Cordova app. I am using SignalR 2 to handle the communication.
The thing I am struggling with is getting a message to a particular user. Every single example out there shows saving Context.User.Identity.Name, which is useless to me because the remote site's User.Identity context is not shared by my phonegap app.
In essence, I am not authenticating a user in the traditional sense, so I need another way of linking the SignalR connectionID with the username I pass along.
Taken from the official ASP.NET signalr Examples, I have the following code which overrides the OnConnected event. Unfortunately it takes no parameters and expects User.Identity to be not null:
public override Task OnConnected()
{
using (var db = new UserContext())
{
// Retrieve user.
var user = db.Users
.Include(u => u.Rooms)
.SingleOrDefault(u => u.UserName == Context.User.Identity.Name);
// If user does not exist in database, must add.
if (user == null)
{
user = new User()
{
UserName = Context.User.Identity.Name
};
db.Users.Add(user);
db.SaveChanges();
}
else
{
// Add to each assigned group.
foreach (var item in user.Rooms)
{
Groups.Add(Context.ConnectionId, item.RoomName);
}
}
}
return base.OnConnected();
}
Now, maybe what I'd need is to have a version of this method that takes a string as a parameter and then I'd use that as my user identifier.
But how to go about that?
You need to create a new IUserIdProvider for the user and use dependency injection to register your provider and use it.
public interface IUserIdProvider
{
string GetUserId(IRequest request);
}
Register your provider with Global Host
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new MyIdProvider());
Usage:
public class MyHub : Hub
{
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}
}
Taken from: http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#IUserIdProvider