Java方法在预定时间后没有执行

时间:2012-03-19 02:18:19

标签: java android multithreading android-intent handler

我想在启动Intent后10秒执行一个方法:

Intent launchIntent = getPackageManager().getLaunchIntentForPackage(GOOGLE_VOICE_SEARCH_PACKAGE_NAME);
      startActivity(launchIntent);

      final Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          SonrLog.d(TAG, "TIMEOUT, reconnecting!");
          reconnectSONR();
        }
      }, 10000); //10 second timeout

Intent启动,我的代码跨过Handler,但没有打印或被调用。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

好吧,我尝试了上面的代码,它工作正常。我可以看到日志中打印的日志Log.d(TAG, "TIMEOUT, reconnecting!");。我用的代码。

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent launchIntent = getPackageManager().getLaunchIntentForPackage(GOOGLE_VOICE_SEARCH_PACKAGE_NAME);
              startActivity(launchIntent);

              final Handler handler = new Handler();
              handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                  Log.d(TAG, "TIMEOUT, reconnecting!");
                }
              }, 10000); //10 second timeout

        }
    });

注意:GOOGLE_VOICE_SEARCH_PACKAGE_NAME指向其他包,因为它仅用于测试。