Can AsyncTask run inside a service and write to the database?

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(); } } } 

I want to start a service that inserts a value into a table in a sql database. If there is no internet connection, I want him to wait 5 minutes, and then restart the service.

The problem in the code is in SQLiteDatabase db = dbs.getWritableDatabase (); Can I evaluate db inside a service? If so, how do I get me to run the code? thanks

+4
source share
2 answers

Got it to work ... need this.dbs = new DBAdapter (getApplicationContext ());

+2
source

Yeah why not. Use the usual way. Remember to add SQLiteDatabse.setLockingEnabled (true); so that database connection flows are safe!

PS I do not see where you start asyncTask?

+2
source

All Articles