Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 我们应该在实用程序类中有一个静态的最终处理程序吗_Android - Fatal编程技术网

Android 我们应该在实用程序类中有一个静态的最终处理程序吗

Android 我们应该在实用程序类中有一个静态的最终处理程序吗,android,Android,我将编写一个实用程序类,通过在internet上发布消息来报告错误消息。因此,它可以被应用程序中的任何类和任何位置使用。我将这样做: public class Reporter { private static final Handler REPORTER_HANDLER = new Handler(); private Reporter(){} public static void report(final Exception e) { REPORT

我将编写一个实用程序类,通过在internet上发布消息来报告错误消息。因此,它可以被应用程序中的任何类和任何位置使用。我将这样做:

public class Reporter {
    private static final Handler REPORTER_HANDLER = new Handler();

    private Reporter(){}

    public static void report(final Exception e) {
        REPORTER_HANDLER.post(new Runnable() {
            @Override
            public void run() {
                // Using HttpURLConnection to post the message to server.
            }
        });
    }
}
Reporter.getSharedInstance().report(e);

如果我这样做,我认为这不是一个好主意,有人能告诉我如何改进此代码。

这是我创建单例的方法:

public class Reporter {
    private static Reporter mReporter;

    public static initialize(){
        mReporter = new Reporter(); 
    }

    public static Reporter getSharedInstance(){
        return mReporter;
    }

    public void report(final Exception e) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                // Using HttpURLConnection to post the message to server.
            }
        });
    }
}
在应用程序类或主活动类中初始化一次:

Reporter.initialize();
在任何地方都可以这样使用:

public class Reporter {
    private static final Handler REPORTER_HANDLER = new Handler();

    private Reporter(){}

    public static void report(final Exception e) {
        REPORTER_HANDLER.post(new Runnable() {
            @Override
            public void run() {
                // Using HttpURLConnection to post the message to server.
            }
        });
    }
}
Reporter.getSharedInstance().report(e);

在我看来,您缺少
处理程序的概念。您根本不需要处理程序,至少在您提到的用例中是这样

如果您想稍后发布一些操作,那么处理程序将是合适的

如果您希望在其他线程上运行代码时在UI线程上执行某些操作,则可以使用线程处理程序


但是在您的用例中,您只需要执行一些操作,根本不需要与
处理程序
交互。

为什么您一定需要
处理程序
呢?您似乎不理解
处理程序
@Tan-Tran的目的:您甚至可以使用不带处理程序的单例类来实现这一点。因为您只是将数据发布到服务器,所以不需要创建新的实用程序类。只需在应用程序类中创建方法,即可将错误报告发送到服务器。@Tan Tran您是否检查了我的答案?