我正在尝试为 Android 制作社交网络应用程序。我的问题是用户登录时如何维护用户会话?
请帮我找到上述问题的解决方案。
尝试
public class Session {
private static String sessionId;
private static String userRole;
public static void setSessionId(String sessionId) {
Session.sessionId = sessionId;
}
public static String getSessionId() {
return sessionId;
}
}
使用此类并将其导入其他所有活动。您可以定义自己的函数来维护您的特定会话数据
使用 SharedPreferences 创建会话。
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
现在,当你想像这样使用这个类时,在制作这个类之后,让这个类成为对象
private Session session;//global variable
session = new Session(cntx); //in oncreate
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
now when ever u want to get username then same work for session object and call this
session.getusename();
祝你好运:) 密码相同
请看上面的链接。它的细节相当好。
使用单例来维护用户会话。
我DefaultHttpClient
使用HttpRequestInterceptor
和HttpResponseInterceptor
。与此类似的东西:
public class HTTPClients {
private static DefaultHttpClient _defaultClient;
private static String session_id;
private static HTTPClients _me;
private HTTPClients() {
}
public static DefaultHttpClient getDefaultHttpClient(){
if ( _defaultClient == null ) {
_defaultClient = new DefaultHttpClient();
_me = new HTTPClients();
_defaultClient.addResponseInterceptor(_me.new SessionKeeper());
_defaultClient.addRequestInterceptor(_me.new SessionAdder());
}
return _defaultClient;
}
private class SessionAdder implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context)
throws HttpException, IOException {
Log.d("SessionKeeper", "Adding session with the following string: " + session_id);
if ( session_id != null ) {
request.setHeader("Cookie", session_id);
}
}
}
private class SessionKeeper implements HttpResponseInterceptor {
@Override
public void process(HttpResponse response, HttpContext context)
throws HttpException, IOException {
Header[] headers = response.getHeaders("Set-Cookie");
if ( headers != null && headers.length == 1 ){
Log.d("SessionKeeper", "Keeping session with the following string: " + headers[0].getValue());
session_id = headers[0].getValue();
}
}
}
}
当我尝试发送该会话 id 时,我在我的 android 客户端遇到了类似的问题,服务器端正在创建一个新会话......但是你在 android 客户端检查你没有创建 DefaulthttpClient 两次......只创建一次 httpclient 说主要活动并传递其他活动中的对象......不要创建第二个 HttpClient