如何将Toast放入Runnable of Service中?

时间:2012-01-07 11:45:22

标签: android service toast runnable

我有一个服务,其中包含一个Timer和TimerTask,用于在一段时间内从Webservice接收数据。一切都很好,除了吐司。我想在procSendMapMovements中向用户显示Toast,但我得到了异常。我怎样才能使用Toast?

class taskSendMapMovements extends TimerTask {
        @Override
        public void run() {
            hhSendMapMovements.sendEmptyMessage(0);
        }
    };



    // /////////////////////

    final Runnable rSendMapMovements = new Runnable()
    {
        public void run()
        {
            procSendMapMovements();
        }
    };

    final Handler hhSendMapMovements = new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            performOnBackgroundThread(rSendMapMovements);

            return false;
        }
    });

    // /////////////////////

    public void procSendMapMovements() {
        try {


            Toast.makeText(SrvDataExchange.this,
                    "some texts"
                    Toast.LENGTH_SHORT).show();
// exception here
// my process


        } catch (Exception e) {


        }
    }


@Override
    public void onStart(Intent intent, int startId) {
        try {



            timerSendMapMovements = new Timer();


            timerSendMapMovements
                        .schedule(new taskSendMapMovements(),
                                10*60*1000,
                                10*60*1000);

            //

        } catch (NumberFormatException e) {
            Toast.makeText(this, "error running service: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "error running service: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }



public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }

2 个答案:

答案 0 :(得分:2)

创建一个处理程序以显示吐司。

使用以下内容:

您要显示土司呼叫:

//printToast.sendEmptyMessage();//If you dont want to send no paramter
//if you want to send some object to handler
/*
Message msg=printToast.obtainMessage();
msg.obj=objToSent;
printToast.sendMessage(msg);
*/
final Handler printToast= new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Toast.makeText....;

        }
    });

答案 1 :(得分:1)

**

Handler printToast= new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            Toast.makeText....;
        }
    });
your Runnable
{

   run()
   {

      do what ever you want 
      printToast.sendMessage(printToast.obtainMessage());
        }

}

**