【发布时间】:2017-06-11 13:17:22
【问题描述】:
我想优化我的 android 应用程序中的内存。我将生命周期方法实现为 onCreate(),在其中创建对象,在 onStart() 中设置侦听器并调用方法,并在 onDestroy() 将变量和对象设置为 null 并手动调用垃圾收集器时使用 System. gb(),这是优化 MainActivity 内存的好习惯吗?
public class MainActivity extends AppCompatActivity {
private static final String TAG = Registrazione.class.getSimpleName();
private ProgressDialog pDialog;
private Button btnAccedi;
private EditText email, password;
private TextView linkPasswordDimenticata, linkRegistrazione;
private SessionManager session;
private SQLiteHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication myApplication = new MyApplication();
myApplication.attachBaseContext(getApplicationContext());
setContentView(R.layout.activity_main);
btnAccedi = (Button) findViewById(R.id.button_login);
email = (EditText) findViewById(R.id.email_login);
password = (EditText) findViewById(R.id.password_login);
linkRegistrazione = (TextView) findViewById(R.id.textview_registrazione);
linkPasswordDimenticata = (TextView) findViewById(R.id.textview_password);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
}
@Override
protected void onStart() {
super.onStart();
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(MainActivity.this, Tabbed.class);
startActivity(intent);
this.finish();
}
btnAccedi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (UtilityNetwork.isOnline())
login();
else {
Toast.makeText(getBaseContext(), "Connessione assente", Toast.LENGTH_LONG).show();
}
}
});
linkRegistrazione.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityRegistrazione();
}
});
linkPasswordDimenticata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityPasswordDimenticata();
}
});
}
private void startActivityRegistrazione() {
Intent intent = new Intent(getApplicationContext(), Registrazione.class);
startActivity(intent);
this.finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
btnAccedi = null;
email = null;
password = null;
linkRegistrazione = null;
linkPasswordDimenticata = null;
pDialog = null;
db = null;
System.gc();
}
【问题讨论】:
标签: java android memory-management activity-lifecycle