在服务中写入数据库

Writing to database within a Service

在我的 Android 应用程序中,用户可以收到包含我想存储在 SQLite 数据库中的序列号的通知。但是,我看到在 Service 内写入数据库可能不安全,因为它可以与当前 Activity.

中的其他实例竞争

Service内写数据库真的不安全吗?有什么解决方法吗?

不,如果您使用相同的数据库连接实例,则不会不安全。

Reference

我不知道你所说的 "as it can compete with others instances of it" 到底是什么意思。只需使用更新数据库的方法创建一个服务,并在需要时启动它(并在工作完成后停止它)。

将您的 SQLiteOpenHelper 实现为单例。

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static MyDatabaseHelper instance;

    public static MyDatabaseHelper getInstance(Context context){
        if ( instance == null ){
            instance = new MyDatabaseHelper(context);
        }
        return instance;
    }

}

查看 SQLite 预写日志记录

There are advantages and disadvantages to using WAL instead of a rollback journal. Advantages include:

  1. WAL is significantly faster in most scenarios.
  2. WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently.
  3. Disk I/O operations tends to be more sequential using WAL.
  4. WAL uses many fewer fsync() operations and is thus less vulnerable to problems on systems where the fsync() system call is broken.

来源:https://www.sqlite.org/wal.html

Android(API 11+ 级):

The best way to enable write-ahead logging is to pass the ENABLE_WRITE_AHEAD_LOGGING flag to openDatabase(String, SQLiteDatabase.CursorFactory, int). This is more efficient than calling enableWriteAheadLogging().

SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
    SQLiteDatabase.CREATE_IF_NECESSARY |
    SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
    myDatabaseErrorHandler);

db.enableWriteAheadLogging();

来源 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#enableWriteAheadLogging()