Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.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_Toast_Intentservice - Fatal编程技术网

Android 如果上下文是相同的,那么在安卓系统中,在何处制作祝酒词又有什么关系呢?

Android 如果上下文是相同的,那么在安卓系统中,在何处制作祝酒词又有什么关系呢?,android,toast,intentservice,Android,Toast,Intentservice,我有一个传统尝试使用Toast消息来显示错误消息。1我希望显示这些消息,并添加了代码以使它们进入正确的线程。最简单的更改是传入构造的对象,然后在UI线程上显示它。但是,只有当我在发布的runnable中设置了Toast时,才会显示Toast,而不是如果我传入了一个预先制作的Toast 这项工作: @Override protected void onHandleIntent(Intent intent) { showToast("Error", Toast.LENGTH_LONG); }

我有一个传统尝试使用Toast消息来显示错误消息。1我希望显示这些消息,并添加了代码以使它们进入正确的线程。最简单的更改是传入构造的对象,然后在UI线程上显示它。但是,只有当我在发布的runnable中设置了Toast时,才会显示Toast,而不是如果我传入了一个预先制作的
Toast

这项工作:

@Override
protected void onHandleIntent(Intent intent) {
    showToast("Error", Toast.LENGTH_LONG);
}

private void showToast(final String msg, final int duration) {
    new Handler(getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            // Make and show the toast in the posted runnable
            Toast.makeText(getApplicationContext(), msg, duration).show();
        }
    });
}
不起作用

@Override
protected void onHandleIntent(Intent intent) {
    // Make the toast here
    Toast myToast = Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG);
    showToast(myToast);
}

private void showToast(final Toast toast) {
    new Handler(getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            // Show the toast here
            toast.show();
        }
    });
}
在这两种情况下,上下文都是应用程序上下文,我在源代码中没有看到任何会导致一个版本工作的内容,但另一个版本不工作。相反,后者有着与直接在IntentService中显示Toast相同的问题:“Handler(android.os.Handler){…}向死线程上的处理程序发送消息”,Toast没有消失,等等

为什么吐司必须在主线上制作,而不是在主线上显示


一,。Legacy=我不认为在Toasts中显示错误消息是一个很好的UI,我也不认为服务直接向用户显示消息是一个好主意,但这就是我收到的代码,我想让它变得更好。

在您发布的第二个代码中,Toast是在后台线程中创建的,该线程设置了一个循环器和处理程序(即IntentService点)

toast使用当前线程的循环器创建处理程序,但一旦IntentService在onHandleIntent中完成处理工作,它就会停止自身(如果没有其他要处理的意图)-销毁toast处理程序所依赖的线程

第327行:


在runnable中制作toast是可行的,因为此时,当前线程是UI线程。

这看起来确实是问题的根源。我想知道他们是在那里而不是更靠近需要它的地方。在这一点上,对于一个非常简单的对象来说,似乎是不必要的复杂化。