How to declare global variables in Android?

前端 未结 17 3372
死守一世寂寞
死守一世寂寞 2020-11-21 04:12

I am creating an application which requires login. I created the main and the login activity.

In the main activity onCreate method I added the following

17条回答
  •  佛祖请我去吃肉
    2020-11-21 05:06

    You can do this using two approaches:

    1. Using Application class
    2. Using Shared Preferences

    3. Using Application class

    Example:

    class SessionManager extends Application{
    
      String sessionKey;
    
      setSessionKey(String key){
        this.sessionKey=key;
      }
    
      String getSessisonKey(){
        return this.sessionKey;
      }
    }
    

    You can use above class to implement login in your MainActivity as below. Code will look something like this:

    @override 
    public void onCreate (Bundle savedInstanceState){
      // you will this key when first time login is successful.
      SessionManager session= (SessionManager)getApplicationContext();
      String key=getSessisonKey.getKey();
      //Use this key to identify whether session is alive or not.
    }
    

    This method will work for temporary storage. You really do not any idea when operating system is gonna kill the application, because of low memory. When your application is in background and user is navigating through other application which demands more memory to run, then your application will be killed since operating system given more priority to foreground processes than background. Hence your application object will be null before user logs out. Hence for this I recommend to use second method Specified above.

    1. Using shared preferences.

      String MYPREF="com.your.application.session"
      
      SharedPreferences pref= context.getSharedPreferences(MyPREF,MODE_PRIVATE);
      
      //Insert key as below:
      
      Editot editor= pref.edit();
      
      editor.putString("key","value");
      
      editor.commit();
      
      //Get key as below.
      
      SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
      
      String key= getResources().getString("key");
      

提交回复
热议问题