2013-10-21 51 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."); 
     } 
    }