I have a login in my application. I want to know the best way to set a global session or equivalent that I can refer to from any activity so that they will know if a user is logged in. Also, so that other activities can get the user id to do database transactions.
I don't want to use putExtra() as I will have to开发者_运维技巧 do it for every Intent I build across the application.
You can create an Application class which can be used as a global state holder.
Here's some sample code:
public class SampleApplication extends Application {
private static String username;
private static String password;
@Override
public void onCreate() {
super.onCreate();
username="";
password="";
}
public static String getUsername() {
return username;
}
public static void setUsername(String username) {
SampleApplication.username = username;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
SampleApplication.password = password;
}
}
After declaring static methods and variables, you should define your application class in your AndroidManifest.xml. Use the android:name
attribute of the application
tag in order to define your class name.
Here's some more sample code:
<application
android:name=".SampleApplication"
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SampleApp"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Your application class will share all the life cycle events as that of Activity and will get destroyed when the application exits.
You can access your application variables with static getters and setters from any activity or service:
SampleApplication.setUsername("");
String currentUserName=SampleApplication.getUsername();
SampleApplication.setPassword("");
String currentPassword=SampleApplication.getPassword();
You can also, rather than going for singleton class, opt for the normal class of Application
Alternative to the same example:
public class SampleApplication extends Application {
private String username;
private String password;
@Override
public void onCreate() {
super.onCreate();
username="";
password="";
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
SampleApplication.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
SampleApplication.password = password;
}
}
You can access these with:
((SampleApplication)getApplication()).getUsername();
精彩评论