在服务中以特定间隔运行吐司

时间:2015-05-21 06:20:46

标签: java android multithreading service handler

我试图以2秒的间隔从服务中显示祝酒词。 这个正常的代码工作正常。这只是一个展示吐司的测试。

    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        new Thread(new ToastRunner(this)).start();

        return START_STICKY;
    }

但是下面的代码崩溃了......

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        new Thread(new ToastRunner(this)).start();

        return START_STICKY;
    }


    class ToastRunner implements Runnable{
        Context context;

        public ToastRunner(Context context){
            this.context = context;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Toast.makeText(context, "Service Started", Toast.LENGTH_SHORT).show();

                    Thread.sleep(2000);
                }
            }catch (Exception e){
                Log.d("tag", e.toString() );
            }
        }
    }

java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序

3 个答案:

答案 0 :(得分:1)

试试这段代码,

while (true) {
       new Handler(Looper.getMainLooper()).post(new Runnable() {
       @Override
       public void run() {
             Toast.makeText(context, "Service Started", Toast.LENGTH_SHORT).show();
            }
        });
        Thread.sleep(2000);
      }

答案 1 :(得分:0)

这意味着您无法从另一个线程访问ui元素。你必须使用uiThred。试试这段代码,

           while (true) {
                   runOnUiThread(new Runnable() {

                      @Override
                      public void run() {

                        Toast.makeText(context, "Service Started", Toast.LENGTH_SHORT).show();

                        Thread.sleep(2000);
                      }
                    }
           }

答案 2 :(得分:-1)

尝试这样......

@Override
public void run() {
  try {
    // preparing a looper on current thread    
    // the current thread is being detected implicitly
    Looper.prepare();


// now, the handler will automatically bind to the
// Looper that is attached to the current thread
// You don't need to specify the Looper explicitly
handler = new Handler();

// After the following line the thread will start
// running the message loop and will not normally
// exit the loop unless a problem happens or you
// quit() the looper (see below)
Looper.loop();


 } 
catch (Throwable t) {
    Log.e(TAG, "halted due to an error", t);
  }
}