簡體   English   中英

如何從后台線程顯示吐司消息

[英]How to show toast message from background thread

考慮以下代碼。 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();
            }
}

在主/UI 線程中做 UI 的事情。 試試這個:

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

handler.post(new Runnable() {

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

我寫了一個類來顯示來自后台進程的Toasts 可以在任何地方使用,例如在AsyncTask 您只需要創建此類的一個實例,例如

ToastHandler mToastHandler = new ToastHandler(yourContext);

然后調用showToast()用文字或資源ID和Toast's持續時間就像你通常會用makeToast()

這是代碼或直接下載鏈接

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

您應該能夠使用 getApplicationContext() 方法來獲取用於顯示 Toast 的上下文。

請參閱getApplication() 與 getApplicationContext()以了解有關此問題的一些很好的討論。

getApplicationContext()替換單詞this然后會出現消息

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

正確的 :

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

您不能在不是活動的 ui 線程的線程上顯示 Toast。
如果您使用runOnUiThread方法,則只能在其他地方運行它,以便它在 ui 線程上運行

看看這個問題
Android:在線程中吐司

我們為此目的使用處理程序,因為它很容易...... :)

腳步:

  1. 在主活動(onCreate)中聲明一個處理程序
  2. 一個在后台運行的類,它創建一個參數化的構造函數。 以 Context 為邊界。
  3. 現在從主活動創建一個線程並傳遞該活動的上下文。
  4. 現在從另一個線程發布到處理程序(從你想發送的任何線程)
  5. 現在在 Toast 中使用此上下文,而不是使用 getApplicationContext()

它運行良好。

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

getBaseContext()替換this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM