9

I realise this question has been asked many times, but I am still unable to completely understand this concept. In my application, I am using a static utility class to keep common methods (like showing error dialogs)

Here is how my static class looks like:

    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);

    }

    }

In my main activity, I call this function like this

GlobalMethods.showSimpleAlertDialog(this, R.string.error_msg_failed_load, true);

Is this a good approach? Does this cause memory leaks? If yes, please guide me on the best practices on using utility classes

4

1 回答 1

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

于 2013-09-18T06:28:52.770 回答