0

我正在研究我IntentService的,我在其中循环生成值。在覆盖方法onStartCommand()onDestroy()中,可以使用 显示消息ToastToast我也想在 中使用onHandleIntent(),但它不起作用。我知道有更好的方法(文件、属性等)来显示值,但我需要这些值,当它们被创建时。最终没有(仅用于控制,如果它工作正常)。拜托,你能帮我找出问题吗?提前致谢。

public class HelloIntentService extends IntentService {

  public HelloIntentService() {
      super("HelloIntentService");
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
      return super.onStartCommand(intent,flags,startId);
  }

  @Override
  protected void onHandleIntent(Intent intent) {

      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }}

  @Override
  public void onDestroy()
  {
      Toast.makeText(this, "Service is being destroyed now.", Toast.LENGTH_SHORT).show();
  }
}
4

1 回答 1

0

onHandleIntent 根据源代码在后台的单独线程上运行,因此没有任何更新 UI 的能力。我建议使用日志语句,而不是 Toasts 来显示您的信息:

Log.d("HelloIntentService","service starting");
于 2013-02-25T23:20:44.810 回答