AsyncTask可以在服务中运行并写入数据库吗?

时间:2011-06-16 08:49:51

标签: android sqlite android-asynctask

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分钟,然后再次运行该服务。

代码中的问题出在SQLiteDatabase db = dbs.getWritableDatabase(); 我可以评估服务中的数据库吗?如果是这样,我如何让我运行代码?感谢

2 个答案:

答案 0 :(得分:2)

是的,为什么不呢。使用常规方式。别忘了添加SQLiteDatabse.setLockingEnabled(true);使数据库连接线程安全!

P.S。我看不到你在哪里启动asyncTask?

答案 1 :(得分:2)

让它工作......需要this.dbs = new DBAdapter(getApplicationContext());