我是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基本相同(只有父级不同)。所以我有重复的代码 - 如何避免它?
答案 0 :(得分:1)
您可以将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();
}
...