2013-10-21 88 views
5

我有一個嚴重的方法從sqlite數據庫中提取數據的類。我想「強制」這個類的用戶在一個線程或一個asynctask中調用這些方法。如何從主線程執行方法時拋出異常

如何防止方法在主線程上運行?

我想實現類似於當您嘗試在UI線程上執行某些聯網時拋出的android.os.NetworkOnMainThreadException。

回答

0

看到活套文件,檢查你是在UI線程中運行或不

3
if (Looper.getMainLooper().equals(Looper.myLooper())) { 
    throw new MyException("Don't do it on the UI thread"); 
} 

試試這個它應該工作。當然,創建自己的例外或使用現有的例外。

4

從谷歌凌空庫:

private void throwIfOnMainThread() { 
     if (Looper.myLooper() == Looper.getMainLooper()) { 
      throw new IllegalStateException("Must not be invoked from the main thread."); 
     } 
    }