开发者

Can AsyncTask be run inside a service and write to 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&开发者_StackOverflowgt; {
        @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 run a service which inserts a value into a table in sql database. If there is no internet connection i want it to wait 5 minutes and then run the service again.

The issue in the code is at SQLiteDatabase db = dbs.getWritableDatabase(); Can i assess the db within a service? If so how do i make me code run? thanks


Yes, why not. Use the regular way. Don't forget to add SQLiteDatabse.setLockingEnabled(true); to make the database connection thread safe!

P.S. I can not see where do you start the asyncTask?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜