java 如何从后台线程显示吐司消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7378936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:43:37  来源:igfitidea点击:

How to show toast message from background thread

javaandroid

提问by Asif Rafiq

Consider the following code. In Service.onStart()method i have created and started a thread that should show Toast message but it is not working!

考虑以下代码。在Service.onStart()方法中,我创建并启动了一个应该显示 Toast 消息的线程,但它不起作用!

public class MyService extends Service{

    private static final String TAG = "MyService";  
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;    
    }       

    @Override   
    public void onCreate()
    {   
    Toast.makeText(this, "My Service Created", Toast.LENGTH_SHORT).show();
         }  
    @Override
    public void onDestroy() 
    {   
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_SHORT).show();  
    }   
    @Override
    public void onStart(Intent intent, int startid)
    {
      Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
      DBIteratorThread dbThread=new DBIteratorThread();
      dbThread.myService=this;
      Thread t1 = new Thread(dbThread);
           t1.start();
    }

}
class DBIteratorThread  implements Runnable
{

    MyService myService;

    public void run()
    {
    //  Toast.makeText(myService, "Thread is Running", Toast.LENGTH_SHORT).show();
            }
}

回答by Matheus Henrique da Silva

Do UI stuffs in main/UI thread. Try this:

在主/UI 线程中做 UI 的事情。试试这个:

Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {

        @Override
        public void run() {
            //Your UI code here
        }
    });

回答by kaolick

I have written a class for showing Toastsfrom background processes. Can be used everywhere, e.g. in an AsyncTask. You only have to create an instance of this class like

我编写了一个用于Toasts从后台进程显示的类。可以在任何地方使用,例如在AsyncTask. 您只需要创建此类的一个实例,例如

ToastHandler mToastHandler = new ToastHandler(yourContext);

and then call showToast()with your text or resource id and the Toast'sduration like you normally would with makeToast().

然后showToast()使用您的文本或资源 ID 以及Toast's您通常使用makeToast().

Here is the code or the direct download link:

这是代码或直接下载链接

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

/**
 * A class for showing a <code>Toast</code> from background processes using a
 * <code>Handler</code>.
 * 
 * @author kaolick
 */
public class ToastHandler
{
    // General attributes
    private Context mContext;
    private Handler mHandler;

    /**
     * Class constructor.
     * 
     * @param _context
     *            The <code>Context</code> for showing the <code>Toast</code>
     */
    public ToastHandler(Context _context)
    {
    this.mContext = _context;
    this.mHandler = new Handler();
    }

    /**
     * Runs the <code>Runnable</code> in a separate <code>Thread</code>.
     * 
     * @param _runnable
     *            The <code>Runnable</code> containing the <code>Toast</code>
     */
    private void runRunnable(final Runnable _runnable)
    {
    Thread thread = new Thread()
    {
        public void run()
        {
        mHandler.post(_runnable);
        }
    };

    thread.start();
    thread.interrupt();
    thread = null;
    }

    /**
     * Shows a <code>Toast</code> using a <code>Handler</code>. Can be used in
     * background processes.
     * 
     * @param _resID
     *            The resource id of the string resource to use. Can be
     *            formatted text.
     * @param _duration
     *            How long to display the message. Only use LENGTH_LONG or
     *            LENGTH_SHORT from <code>Toast</code>.
     */
    public void showToast(final int _resID, final int _duration)
    {
    final Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
        // Get the text for the given resource ID
        String text = mContext.getResources().getString(_resID);

        Toast.makeText(mContext, text, _duration).show();
        }
    };

    runRunnable(runnable);
    }

    /**
     * Shows a <code>Toast</code> using a <code>Handler</code>. Can be used in
     * background processes.
     * 
     * @param _text
     *            The text to show. Can be formatted text.
     * @param _duration
     *            How long to display the message. Only use LENGTH_LONG or
     *            LENGTH_SHORT from <code>Toast</code>.
     */
    public void showToast(final CharSequence _text, final int _duration)
    {
    final Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
        Toast.makeText(mContext, _text, _duration).show();
        }
    };

    runRunnable(runnable);
    }
}

回答by RandomSort

You should be able to use the getApplicationContext() method to get the context with which to show the Toast.

您应该能够使用 getApplicationContext() 方法来获取用于显示 Toast 的上下文。

See getApplication() vs. getApplicationContext()for some nice discussion on this.

请参阅getApplication() 与 getApplicationContext()以了解有关此问题的一些很好的讨论。

回答by mohamed isam

replace word thiswith getApplicationContext()The message will then appear

将单词替换thisgetApplicationContext()消息将出现

Toast.makeText(this, "My Service Created", Toast.LENGTH_SHORT).show();

the correct :

正确的 :

Toast.makeText(getApplicationContext(), "My Service Created", Toast.LENGTH_SHORT).show();

回答by chrmcpn

You can't show a Toast on a thread that is not the activity's ui thread.
you can only run it somewhere else if you use runOnUiThreadmethod so that it runs on the ui thread

您不能在不是活动的 ui 线程的线程上显示 Toast。
如果您使用runOnUiThread方法,则只能在其他地方运行它,以便它在 ui 线程上运行

Look at this question
Android: Toast in a thread

看看这个问题
Android:在线程中吐司

回答by Raj Kumar

We use handler for this purpose because it is easy... :)

我们为此目的使用处理程序,因为它很容易...... :)

Steps:

脚步:

  1. declare a handler in the main activity (onCreate)
  2. a class which is to be run in the background in that create a parameterized constructor . Taking the Context a perimeter .
  3. now create a thread from the main activity and pass the Context of that activity.
  4. now Post to the handler from that another thread (from whichever thread u want to send)
  5. now use this context in the Toast, instead of using getApplicationContext()
  1. 在主活动(onCreate)中声明一个处理程序
  2. 一个在后台运行的类,它创建一个参数化的构造函数。以 Context 为边界。
  3. 现在从主活动创建一个线程并传递该活动的上下文。
  4. 现在从另一个线程发布到处理程序(从你想发送的任何线程)
  5. 现在在 Toast 中使用此上下文,而不是使用 getApplicationContext()

It runs well.

它运行良好。

mhandler.post(new Runnable() {
    public void run() {
        Toast.makeText(context,"Run ends",Toast.LENGTH_LONG).show();
    }
});

回答by Ian Low

Substitute thiswith getBaseContext().

替换thisgetBaseContext()