冲突访问sqlite数据库android,来自Service和onClick

时间:2012-10-30 20:19:05

标签: android multithreading sqlite service

在我的app android中,我可以从:

访问我的sqlite数据库

1)服务安卓,每60秒。

2)按钮压力(onclik)

如果我在服务访问数据库时按下按钮,则会发生错误。

所以我在onclickListener中插入,在访问数据库之前,调用stopService()

但是冲突仍然存在,因为即使我在访问数据库之前调用了stopService(),服务也会在此之后停止!

我试过,使用:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager)  getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.MyService".equals(service.service.getClassName())) {
           return true;
        }
    }
    return false;
 }

How to check if a service is running on Android?

中建议

我试图在访问数据库之前以这种方式调用此方法:

    while(isMyServiceRunning())
    {
        // do nothing
    }

    // *** access to my database ***

在访问数据库之前,为了确保我的服务已停止,我该怎么办?

错误是:

10-30 21:05:43.360: E/SQLiteDatabase(13960): Failed to open the database. closing it.
10-30 21:05:43.360: E/SQLiteDatabase(13960):        android.database.sqlite.SQLiteDatabaseLockedException: database is locked
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.database.sqlite.SQLiteDatabase.setLocale(SQLiteDatabase.java:2115)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:984)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:956)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1021)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:753)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149)
10-30 21:05:43.360: E/SQLiteDatabase(13960):    at host.database.DB_DatabaseManager.open(DB_DatabaseManager.java:134)

1 个答案:

答案 0 :(得分:1)

您可以覆盖服务的onDestroy()事件并尝试访问其上的数据库:

@Override
public void onDestroy() {
    // *** access to my database ***
    super.onDestroy();
}