Search code examples
javaandroidkotlinrequest

How To Make Server Request Work Continously In Java?


In my mobile application that I developed with Java, there are two activities named ChatActivity and MainActivity. When the user logs in, he or she is redirected to ChatActivity. However, if the user's token cannot be verified while the user is in ChatActivity, the user must be automatically redirected from ChatActivity to MainActivity instantly.

For the token verification process, I need to send an API request to the server and verify the token every time the user is in ChatActivity. I applied what I said, but there are some problems. For example, the API code in the onCreate method only works when user opens the application, that is, the request isn't send constantly.

I want the token verification process to occur continuously and quickly as in modern applications, that is, if the user's token cannot be verified, I want it to be immediately redirected to MainActivity. How do I achieve this? Here's an example code:

    protected void onCreate(Bundle savedInstance) {
       super.onCreate(savedInstance);
       setContentView(R.layout.activity_chat);
       OkHttpClient client = new OkHttpClient();
       client.newCall(/* ... */).execute();
       // Other fields...

       if (!isTokenVerifed) {
           startActivity(new Intent(ChatActivity.this, MainActivity.class));
           finish();
       }
   }
}

My request code works only once.


Solution

  • You shouldn't do it this way at all. How is your token being unvalidated- most likely time. So send down the expiresAt time along with the token, set a timer, and when it expires log them out. If you're worried about a manual logout from the server, implement push messaging (you'll need that anyway for a chat app) and log them out when a LOGOFF message is sent via push. Polling continuously to check if they're logged out is a waste of network resources on both the client and the server.