Passing reference to activity to utility class android

六眼飞鱼酱① 提交于 2019-12-13 11:36:28

问题


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


回答1:


No, it's a bad approach. You better pass WeakReference<Activity> to your methods, and implement methods like this:

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
    }

Further reading: http://android-developers.blogspot.ae/2009/01/avoiding-memory-leaks.html



来源:https://stackoverflow.com/questions/18865060/passing-reference-to-activity-to-utility-class-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!