更新应用程序后,我需要使用来自互联网的其他数据唯一地填充数据库。为此,我实现了一个名为 OnUpgradeService() 的服务。该服务应该在 SQLiteOpenHelper 的 OnUpgrade() 方法中启动。
我可以看到 startService 已执行,但未调用 onStartCommand() 。
public class MyContentProvider extends ContentProvider {
...
private static class MyOpenHelper extends SQLiteOpenHelper {
...
public MyOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
}
...
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1) {
db.execSQL(DATABASE_CREATE_THUMBNAIL);
db.execSQL("alter table " + DATABASE_TABLE_FRIEND + " add column " + KEY_THUMBNAIL_URI + " text;");
...
Intent intent = new Intent(context, OnUpgradeService.class);
context.startService(intent);
}
else {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FRIEND);
onCreate(db);
}
}
...
public class OnUpgradeService extends Service {
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t = new Thread(new Runnable() {
public void run() {
upgradeDatabase();
stopSelf();
}
});
t.start();
return Service.START_REDELIVER_INTENT;
}
清单中的相关条目如下所示:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >
...
<application>
...
<service android:enabled="true" android:name=".OnUpgradeService" />
...
</application>
...
</manifest>