3

I'm working on an App, where I wanted the user to keep logged-in means always connected to the server after successful login(just like facebook app). I tried to google this but did not found any correct logic of this. Many website suggests to use SharedPreference but keeping the user's login cred. on SheredPreference is not good idea and did not provide any answer to stay connected to the server. I'm kinda stuck with this idea. I just need logic to implement this. Any suggestions and example code are welcome.

I'm android noob.

5 Answers5

4

Storing user's credentials on device is not a good way of designing. You can store the Hash password, which is also denied as good application design technique. According to the facebook and google these tech giants use Authentication token login-logout. Once the user log in server generate token for particular user which is then stored on your device as well as the server. Next time user come to App a request has been made to check the token is valid or not, if valid - access granted else not.

A basic design of this process

enter image description here

Tutorial :

W4R10CK
  • 5,502
  • 2
  • 19
  • 30
1

Firstly, you should ideally be generating a token when a user logs in(facebook app also uses oauth token), which should then be stored on your device as well as the server. Its not a good idea to even store email address or any other such user information on the phone.

Create and maintain a session on the server side. Next, let the app connect to the mothership, i.e. the server after a set interval and send an "I am alive" message. If you get the message on the server side, you bump up the session time.

This way, the user stays logged in forever, but only if the user stays active.

Both server and app must first check session and token before sending or receiving data. This ensures that the user is authorized, that the app was not force closed, and the user still stays connected. Please ask further if you want something more.

  • I understand the concept a little bit, is there any tutorial or code to achieve this? any link to tutorials or example code. thannks –  Sep 22 '16 at 06:42
  • Yeah heres the link. If you find it useful bump my solution up:) https://simpleprogrammer.com/2011/05/25/oauth-and-rest-in-android-part-1/ – digvijaykatoch Sep 22 '16 at 11:31
0

Your question doesn't seems clear.

1) what do you mean by always connected to server?
2) What kind of things you need to do if user is connected to server?

I can suggest you to use SharedPreferences if you want user to be logged in all the time in your app, no need to store credentials of user in SharedPreferences, you can store userId, email address and those kind of details.SharePreferences

If you want some information on time basis like need to update data daily or every hour, you can call API by using AlarmManager for given time.AlarmManager

Still you want some information to notify user about new change/update, you can use Push Notifications.GCM and FCM

Note :

Firebase Cloud Messaging (FCM) is the new version of GCM.

Ravi
  • 34,851
  • 21
  • 122
  • 183
  • Ravi, Thanks for answer. I have 2 app, one for manager and one for worker. Each time when manager sends data(like image, description, latlng, etc) to server, I want the data to be seen by each of the worker for acknowledgement. I want the worker to be logged in(connected to server) always, so that he can access new data coming from manager via server without logging always. Just like facebook app, once you logged in, you logged in and keep receiving data. Any code or example related to this will be helpful. –  Sep 22 '16 at 05:45
  • In that case i will suggest to send push notification to all workers whenver manager sends data. You can also load new data whenever worker and manager opens app. With the push notification move the control to listing screen and there you can load data from API. – Ravi Sep 22 '16 at 05:48
  • Ohkk, after push notification, how to login the worker. I'm kinda noob android developer, please provide any link to this. –  Sep 22 '16 at 06:24
0

First of all I don't understand the use of terms stay connected to server and stay logged in in your case. But to my understanding I will answer this.

  1. To stay logged in, as in, not to ask for the credentials everytime, you are supposed to get a unique token from the server and store it along with other login details (except password) in SharedPreferences or in some database. Whenever user open the app, use the token received as an authentication parameter (you can refer oath method too). This will eliminate the chances of leaking password and token will be specific to device just like sessions.

  2. Stay connected to server, as in, receive instant notifications, send and receive messages? When app is opened, use sockets, that's how it is done, when app is closed, you can use FCM.

Mohammed Atif
  • 4,383
  • 7
  • 28
  • 57
0

Try this its work for me..

sessionManager.java

   package com.example.sachin.splashlogin;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.util.HashMap;

public class SessionManager {

    SharedPreferences pref;

    // Editor for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "SocialPref";

    // All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";

    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "email";

    // Email address (make variable public to access from outside)
    public static final String KEY_ID = "user_id";

    // Constructor
    public SessionManager(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    /**
     * Create login session
     * */
    public void createLoginSession(String email, String userid){
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);

        // Storing name in pref
        editor.putString(KEY_NAME, email);

        // Storing email in pref
        editor.putString(KEY_ID, userid);

        // commit changes
        editor.commit();
    }   

    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     * */
    public void checkLogin(){
        // Check login status
        if(!this.isLoggedIn()){
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, com.example.sachin.splashlogin.Login.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

    }



    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));

        // user email id
        user.put(KEY_ID, pref.getString(KEY_ID, null));

        // return user
        return user;
    }

    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

        editor.putBoolean(IS_LOGIN, false);
        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, Login.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        //_context.startActivity(i);
    }

    /**
     * Quick check for login
     * **/
    // Get Login State
    public boolean isLoggedIn(){
        return pref.getBoolean(IS_LOGIN, false);
    }

}

and in every new screen you just need to paste this code..

 SessionManager session;

paste this code in onCreate()

 session = new SessionManager(getApplicationContext());
        HashMap<String, String> user = session.getUserDetails();
        struid = user.get(SessionManager.KEY_NAME);