我是Java和Android编程的新手。
我刚刚用登录表单和注册表单创建了简单的应用程序。我的登录表格和注册表格现在可以使用。
我创建了从Activity类扩展的抽象SignedActivity类。我希望登录后从SignedActivity继承的每个活动都可用。如果活动是从SignedActivity继承的,那么我可以确定它仅适用于已签名的用户。
这是SignedActivity的外观:
public abstract class SignedActivity extends Activity {
public static String LOG_OUT_PATH = "/logOut.php";
private String sessionId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String newSessionId = savedInstanceState.getString("sessionId");
if (newSessionId instanceof String) {
sessionId = newSessionId;
return;
}
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newSessionId = extras.getString("sessionId");
if (newSessionId instanceof String) {
sessionId = newSessionId;
return;
}
}
finish();
}
public void startSignedActivity(Intent intent) {
intent.putExtra("sessionId", getSessionId());
this.startActivity(intent);
}
protected String getSessionId() {
return sessionId;
}
private void setSessionId(String newSessionId) {
sessionId = newSessionId;
}
protected void logOut() {
new RequestLogOutTask().execute(SignedActivity.LOG_OUT_PATH);
setSessionId("");
Intent intent = new Intent(this, SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("logOut", true);
startActivity(intent);
}
public void onClickLogOut(View v) {
logOut();
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("sessionId", sessionId);
super.onSaveInstanceState(savedInstanceState);
}
class RequestLogOutTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... params) {
(new RESTClient(Constants.REST_URL)).post(params[0], "");
return null;
}
}
}
我的问题是登录后有时需要FragmentActivity而不是Activity。因此,我必须创建从FragmentActivity扩展的SignedFragmentActivity,它基本上与SignedActivity相同(仅父项不同)。所以我有重复的代码-如何避免呢?
最佳答案
您可以将您的SignedActivity
代码移动到ActivityHelper
类:
class ActivityHelper {
public static String initializeSessionId(Bundle savedInstanceState, Activity activity) {
if (savedInstanceState != null) {
String newSessionId = savedInstanceState.getString("sessionId");
if (newSessionId instanceof String) {
return newSessionId;
}
}
Bundle extras = activity.getIntent().getExtras();
if (extras != null) {
String newSessionId = extras.getString("sessionId");
if (newSessionId instanceof String) {
return newSessionId;
}
}
return null;
}
...
}
现在,您可以在每个
Activity
实例(即FragmentActivity
)中使用它:@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionId = ActivityHelper.initializeSessionId(savedInstanceState, this);
finish();
}
...