public class IdService extends Service {
private UploadFilesTask task;
DBAdapter dbs;
@Override
public IBinder onBind(Intent i) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if(Networking.isNetworkAvailable(this)){
if (intent.hasExtra("start") && taskIsNotRunning()) {
task = new UploadFilesTask();
task.execute();
}
}
else{
if (intent.hasExtra("start") && taskIsNotRunning()) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 5);
String start = "start";
Intent i = new Intent(IdService.this, IdService.class);
i.putExtra("start", start);
PendingIntent sender = PendingIntent.getService(this, 192837, i, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
}
}
private boolean taskIsNotRunning() {
return task == null || task.getStatus() != AsyncTask.Status.RUNNING || task.isCancelled();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private class UploadFilesTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... arg0) {
SQLiteDatabase db = dbs.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBAdapter.ID, "blank");
db.insert(DBAdapter.Table, null, values);
return null;
}
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
stopSelf();
}
}
}
我想運行一個服務,它將一個值插入到sql數據庫的表中。如果沒有互聯網連接,我希望它等待5分鐘,然後再次運行服務。AsyncTask可以在服務中運行並寫入數據庫嗎?
代碼中的問題在SQLiteDatabase db = dbs.getWritableDatabase(); 我可以評估服務中的數據庫嗎?如果是這樣,我怎麼讓我的代碼運行?謝謝
你有什麼錯誤?是否有任何其他連接到數據庫? – 2011-06-16 09:27:05
什麼是dbs?你在哪裏啓動它? – 2011-06-16 10:12:15
頂部的第三行 – Beginner 2011-06-16 10:23:36