本文介绍了如何从后台线程显示吐司消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

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填充.试试这个:

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

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

handler.post(new Runnable() {

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

这篇关于如何从后台线程显示吐司消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:14