我意识到这个问题已被多次提出,但我仍然无法完全理解这个概念。在我的应用程序中,我使用静态实用程序类来保留常用方法(如显示错误对话框)
以下是我的静态类的样子:
public class GlobalMethods {
//To show error messages
public static final void showSimpleAlertDialog(final Activity activity, String message, final boolean shouldFinishActivity) {
if (!activity.isFinishing()) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_HOLO_DARK);
builder.setCancelable(true).setMessage("\n" + message + "\n").setNeutralButton(activity.getResources().getString(R.string.label_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
}).setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
if (shouldFinishActivity)
activity.finish();
}
}).show();
}
}
//check for connectivity
public static final boolean isOnline(Context context) {
NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnectedOrConnecting());
}
//for the 'HOME' button on every activity
public static final void goToDashboard(Activity activity) {
goToActivity(ActivityDashboard.class, activity);
}
}
在我的主要活动中,我将此函数称为
GlobalMethods.showSimpleAlertDialog(this, R.string.error_msg_failed_load, true);
这是一个好方法吗?这会导致内存泄漏吗?如果是,请指导我使用实用程序类的最佳实践
答案 0 :(得分:6)
不,这是一个糟糕的方法。
最好将WeakReference<Activity>
传递给您的方法,并实现如下方法:
public static final void showSimpleAlertDialog(final WeakReference<Activity> mReference, String message, final boolean shouldFinishActivity) {
Activity activity = mReference.get();
if (activity != null) {
//your code goes here
}
进一步阅读:http://android-developers.blogspot.ae/2009/01/avoiding-memory-leaks.html