从服务中的线程发送Toast

时间:2012-03-23 03:24:43

标签: android multithreading service toast

我正在尝试在线程中发送错误的Toast通知。线程在从主线程调用的服务中启动。我用View.post和一些奇怪的处理程序东西尝试了几件事,但似乎没什么用。该主题的摘录如下:

    public int onStartCommand(Intent intent, int flags, int startId) 
{
    new Thread(new Runnable(){
        public void run() {
            boolean bol = true;

            while (bol)
            {

                try 
                {
                    //Some socket code...
                } 
                catch (Exception e) 
                {
                 //Where I want the toast code.
                } 
            }

        }
    }).start();

    return START_STICKY;
}

4 个答案:

答案 0 :(得分:6)

尝试在服务中的线程内跟随:

Handler h = new Handler(context.getMainLooper());
     // Although you need to pass an appropriate context
    h.post(new Runnable() {
        @Override
        public void run() {
             Toast.makeText(context,message,Toast.LENGTH_LONG).show();
        }
    });

取自@Alex Gitelman hereAndroid: How can i show a toast from a thread running in a remote service?上给出的答案。这可能对帮助我的人有所帮助。

答案 1 :(得分:2)

Toast只能从UI线程(主线程)显示。要从其他一些线程中显示Toast,您必须使用Handler

Threads, Handlers and AsyncTask

答案 2 :(得分:0)

是的,您应该使用Handler,并将Activity绑定到Service

设置Handler后,您应该执行此操作,

    Message msg = Message.obtain(null, MyActivity.TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(MyActivity.TOAST_MSG, "Toast message");
    msg.setData(bundle);
    try {
        myActivityMessenger.send(msg);
    } catch (RemoteException e) {
        if (D) Log.w(TAG, "Unable to send() the toast message back to the UI.");
        e.printStackTrace();
    }

myActivityMessenger设置为Handler的{​​{1}},并在MyActivity绑定到Service时发送给MyActivity

然而,显示带有Toast作为上下文的Service应该有效(但这不是最好的方式),所以也许是因为你试图从一个新线程中创建它。您制作Toast的代码是什么?

答案 3 :(得分:-1)

    new Thread(){
        @Override
        public void run() {

            runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        _dialog.dismiss();
                        Toast.makeText(LatestNewsActivity.this, "NO Internet Connection Available", Toast.LENGTH_LONG).show();
                    }
                });
            }   
    }.start();