运行 在服务中以特定间隔敬酒

Running toast in at certain interval in a service

我正尝试在服务中以 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()

的线程内创建处理程序

像这样尝试...

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

试试这个代码,

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

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

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

                      @Override
                      public void run() {

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

                        Thread.sleep(2000);
                      }
                    }
           }