代码之家  ›  专栏  ›  技术社区  ›  Nerdy Bunz

如何检查代码是否在后台运行?

  •  1
  • Nerdy Bunz  · 技术社区  · 6 年前

    在Java/Android中,是否有方法检查当前正在执行的代码行是否在后台线程上执行?

    我有一个小节目,我正在变魔术,终于达到了全意大利面阶段。。。你看,这是故意的,因为这样。。。如果竞争对手拿到了密码,他们“打开引擎盖”,看了20多秒,头发就会着火,尖叫着跑掉。。。但现在连我都搞糊涂了,我需要检查一下这种情况。

    附件A:

    // can be called from 1,067 places... some of which are background threads.
    public void startDoingAFunDance(String caller, int wobbleIntensity, int spineAngle, int feetSeparationInInches) {
    
        if (!validCallersForFunDance.contains(caller)) { 
            Log.i("XXX", "Caller not allowed."); 
            return; 
        }
    
        boolean wasCalledFromBackgroundThread = // ? < what to put here > ?
    
        Log.i("XXX", "Was startDoingAFunDance() called from a background thread? And the answer is: " + wasCalledFromBackgroundThread);
    
        // classified
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Lino    6 年前

    一个简单的方法是

    boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
    

    后台线程没有id 1(UI线程有)。