Android 数据库 ANR的例子
android 开启事务之后,在其他线程是不能进行增删改查操作的。例子如下:
首先,一个线程里面去开启事务,里面对数据库的任何操作都没有。
DBAdapter.getInstance().beginTransaction();
long begin = System.currentTimeMillis();
int a = 50;
while(System.currentTimeMillis() - begin < 1000 * 60 * 10){
a=60;
}
DBAdapter.getInstance().setTransactionSuccessful();
DBAdapter.getInstance().endTransaction();
第二步,主线程去查询数据库
cloudBook = DBAdapter.getInstance().queryBookIDWithoutPath(item.mBookID, item.mFile);
第三步,直接卡死
"main" prio=5 tid=1 TimedWaiting
| group="main" sCount=1 dsCount=0 obj=0x7405e578 self=0xf5276500
| sysTid=9309 nice=-4 cgrp=default sched=0/0 handle=0xf74c6b34
| state=S schedstat=( 2038578573 87941787 1472 ) utm=184 stm=19 core=5 HZ=100
| stack=0xff56c000-0xff56e000 stackSize=8MB
| held mutexes=
at java.lang.Object.wait!(Native method)
- waiting on <0x0cc38bc3> (a java.lang.Object)
at java.lang.Thread.parkFor$(Thread.java:1220)
- locked <0x0cc38bc3> (a java.lang.Object)
at sun.misc.Unsafe.park(Unsafe.java:299)
at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:670)
at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:348)
at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:894)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:586)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.zhangyue.iReader.DB.DBAdapter.execSQL(DBAdapter.java:2510)
- locked <0x0faa1c40> (a com.zhangyue.iReader.DB.DBAdapter)
at com.zhangyue.iReader.DB.DBAdapter.queryBookIDWithoutPath(DBAdapter.java:1497)
at com.zhangyue.iReader.read.ui.BookBrowserFragment.isDisplayAddBookShelf(BookBrowserFragment.java:1223)
at com.zhangyue.iReader.read.ui.BookBrowserFragment.access$5600(BookBrowserFragment.java:368)
at com.zhangyue.iReader.read.ui.BookBrowserFragment$20.run(BookBrowserFragment.java:3098)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:5720)
at java.lang.reflect.Method.invoke!(Native method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
可以看到,数据库 at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:670)
在主线程一直在等待链接。
总结
- 事务操作会影响对数据库操作,查询都要等待
- 不要在一大坨代码都放在事务操作里面。
泰山崩于前而色不变的曹新雨,抱歉