send data to server every minute (For check status user) - java

For check status user i should send some data to server every 5 minutes with retrofit2.
Of course, this information should be sent when the user is in the app
This means that when the user is out of the application, there is no need to send something to the server
What is the best way to do this?
For connection to server i use retrofit2.

One solution is to use Android's work manager to ping your server with http request. You can create initial OneTimeWorkRequest when user logins and with in each execution create a new OneTimeWorkRequest with 5 minutes delay. When user exits the app cancel all the work request.
See the Jetpack Library: https://developer.android.com/topic/libraries/architecture/workmanager
Another solution for which you need to make changes in your architecture is to use Sockets with library like SocketIO. Connect the socket from your app when user login notifying server that user is online. When socket disconnect server can mark user offline: https://socket.io/blog/native-socket-io-and-android/
One other solution is to use Firebase Realtime database for presence system. Firebase has nice example of how to do this: https://firebase.googleblog.com/2013/06/how-to-build-presence-system.html

You can write this code in service and make network call every 5 minutes using handler or RxJava;
public class YourService extends Service{
public final Handler handler = new Handler();
#Override
public void onCreate() {
makeCallEvery5Min();
}
private void makeCallEvery5Min(){
runnable = new Runnable() {
#Override
public void run() {
// execute call here
}
handler.postDelayed(runnable, delay);
}
}
}
RXJava
private void makeCallEvery5min() {
Observable.interval(0, 5, TimeUnit.MINUTES)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> your_network_call() );
}

May help you below approach
If user is log in, should have user id.
Now try to check for user id of particular user in user log in session.
Note: below code should be added in web page(jsp or servlet)--.
Single User Approach:if(userId==Session.getUserId(userId)){response.refresh(5);//write code to send data to server using retrofit2.}
MultiUser Approach: multiple users log in.if(Session.getUsers()!=null){response.refresh(5);//write code to send data to server using retrofit2 }

Related

Can you implement autorenewing subscriptions in codenameone without a server side

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.

Sending notifications One to One (Firebase) [duplicate]

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

Spring : Send automated email to member and admin after timer expires

I am working on a Spring-MVC application in which there is Service desk functionality I am working on. So, as a part of Service desk, users can create issues and assign a support-team member. In that, they can also assign in how much time issue needs to be resolved. I am setting the time in java.sql.TimeStamp.
Now, when the time expires, I would like to send an email to the support-team admin, the person who created the issue and the support-team member responsible for resolving the issue.
If it was a normal scheduled or cron job, I can just write a #Scheduled method and get it over with, but here, I would like to check for example after 6 hours if the issue was resolved or not. How do I accomplish that? I have no idea to be honest.
Here is service layer part the SupportRequest :
#Service
#Transactional
public class SupportRequestServiceImpl implements SupportRequestService{
private final SupportRequestDAO supportRequestDAO;
#Autowired
public SupportRequestServiceImpl(SupportRequestDAO supportRequestDAO){
this.supportRequestDAO = supportRequestDAO;
}
#Autowired
private SupportTeamService supportTeamService;
#Override
public int addSupportRequest(SupportRequest supportRequest, int assignedTeamId, Long groupId) {
SupportTeam supportTeam = this.supportTeamService.getSupportTeamMemberById(assignedTeamId);
if(!(supportTeam == null)){
supportRequest.setCreationTime(new Timestamp(System.currentTimeMillis()));
supportRequest.setAssignedTeamMemberId(supportTeam.getTeamId());
return this.supportRequestDAO.addSupportRequest(supportRequest,groupId);
}
return 0;
}
}
I don't know what else to show. Thanks a lot.
Update
Will something like this work?
long delay = 1000*60*60*12; // after 12 hrs
Timer timer = new Timer();
Calendar cal = Calendar.getInstance();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
System.out.println("inside the main");
Integer id = new Integer(10);
Assert.assertNotNull(id);
}
}, delay);
For these kind of scenario, there should be background process running. That process will check for issues that has not been fixed in given time. Then this process will send a message to whoever you want and then continue running in background.
There are different ways of doing this.
1. Batch Process
You can make batch process. Batch process will be running on your server, it will check for expired issues and then send mail to the support-team admin.
2. Techniques for Real-time Updates
You can also you real time update techniques in spring. Using this technique you will fire request after every given period that will check for expire issues. If any issue found that has not been fixed you can send mail. Please read the related document here : Spring MVC 3.2 Preview: Techniques for Real-time Updates
3. Web Socket
Web socked can also be useful for these kind of task. Find the good source here :
SPRING FRAMEWORK 4.0 M2: WEBSOCKET MESSAGING ARCHITECTURES

How to periodically run a task?

I started building my app to send JSON strings to a server, however it is only sent when I click a button. I would like it to be sent automatically after a time that is specified by the user from a TimeDialog. I was suggested to use AlarmManager or Handler, but I do not know how to implement it with my app. I have provided the line of code that will be executes and sends to my server. Any help or suggestions?
Code used I would like it to be run after specified time:
public void onClick(View view) {
switch (view.getId()) {
case R.id.saveBtn:
if (!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().onPostExecute("server_adress"); //was execute but changed!
break;
}
}
You can use Java Util Timer class to do what you want.
you can see here an example.
Try to use it!!!
While an alarm manager/handler is often the best way schedule future events on Android, Google suggests using a Sync Adapter when scheduling network calls like your application synching to the server at a given interval. The framework provides a predefined user authentication, background scheduling so that you app does not need to be running to make the call, improved battery performance, and handling the case when there is no network connectivity at the time scheduled. Here's their developer page on using Synch Adapters.

Recording data in android app and web service at same time

Is it possible to record data in android app and webservice at same time? I am trying to do this but if data is recording in android app data then not recording in webservice and if recording in webservice stops recording in android app? Thx in advance
You're doing a network request on the main thread which is not supported by the Android Version you're using.
Why not ? Assuming we are doing network operation on a button click in our application. On button click a request would be made to the server and response will be awaited. Due to single thread model of android, till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI thread. This includes file and network access.
So start a new Thread when you want to send data. Something like :
new Thread(new Runnable() {
#Override
public void run() {
//Send Data to Web Server Here.
}
}).start();

Categories

Resources