2011-06-16 66 views
3
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(); 我可以評估服務中的數據庫嗎?如果是這樣,我怎麼讓我的代碼運行?謝謝

+0

你有什麼錯誤?是否有任何其他連接到數據庫? – 2011-06-16 09:27:05

+0

什麼是dbs?你在哪裏啓動它? – 2011-06-16 10:12:15

+0

頂部的第三行 – Beginner 2011-06-16 10:23:36

回答

2

得到它的工作...需要this.dbs = new DBAdapter(getApplicationContext());

+0

如何每30秒運行一次服務? – Manikandan 2014-06-10 15:16:27

+0

@Manikandan閱讀此篇文章:http://stackoverflow.com/questions/22043652/using-an-asynctask-inside-a-service-class – ymerdrengene 2014-09-25 14:47:25

2

是的,爲什麼不。使用常規方式。不要忘記添加SQLiteDatabse.setLockingEnabled(true);使數據庫連接線程安全!

P.S.我看不到你在哪裏開始asyncTask?

+0

task.execute(); – Beginner 2011-06-16 10:00:15

相關問題