【问题标题】:Maintain SQLite Database in Intent Service with AsyncTask使用 AsyncTask 在 Intent 服务中维护 SQLite 数据库
【发布时间】:2014-05-13 06:07:49
【问题描述】:

我已经通过以下方式实现了代码向服务器发送新数据从服务器接收新数据

首先接收新数据:

public class ReceivingOrderService extends IntentService {

    public ReceivingOrderService() {
    super("ReceivingDataService");
    // TODO Auto-generated constructor stub
    }

    /*
     * Context Variable
     */
    Context context;

    /*
     * Database Variable
     */
    DatabaseHelper dbHelper;


    /** 
     *  For Sending LastSyncTime to Server 
     **/
    String last_sync_time;

    @Override
    public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
    // TODO Auto-generated method stub
    /*
     * Getting Context Object
     */
    context = getApplicationContext();

    /* 
     * Getting Database Object and Opening DB
     */
    dbHelper = new DatabaseHelper(context);
    dbHelper.open();

    /*
     * Getting last_sync_time
     */
    last_sync_time = dbHelper.getLastSyncTime();

    if(last_sync_time == null)
    {
        this.stopSelf();
        last_sync_time = null;
    }

    new ReceiveDataTask().execute();
    }

    public class ReceiveDataTask extends AsyncTask<Void,Integer,JSONObject>
    {

        /***********
         *
         *
         * PROCESS for RECEIVING and UPDATING DB
         *
         *
         ***********/

        /**** DATABASE CLOSING *****/

        /**** starting Service for Sending New Data *****/
    }
}

然后发送数据:

public class SendingOrderService extends IntentService {
   new SendingDataTask().execute();
}

public class SendDataTask extends AsyncTask<Void,Integer,JSONObject>
{

}

一切进展顺利,但有时应用程序会因为数据库而出现Force Close 错误。

我认为当我同时查询数据库时会出现问题 时间服务也会调用数据库。

  1. IntentService 中的数据库维护有问题吗?还有其他方法吗?

  2. 我可以不使用 AsyncTask 直接向服务器发送请求吗?

您的帮助将不胜感激。

【问题讨论】:

  • 如果发生崩溃,请从 logcat 发布堆栈跟踪。
  • 为什么在意图服务中需要异步任务?
  • 您不需要 IntentService 中的 AsyncTask。 onHandleIntent 中的所有代码都将在后台线程上执行。
  • 好的。我已删除 AsyncTask 并将整个代码发布到 onHandleIntent。我的另一个问题是数据库将如何在服务中维护。
  • 小心 sqllite 操作阻塞了 UI 线程。如果您打算将 IntentService 用作后台线程并保持 UI 响应,请注意对数据库进行简短且少量的操作...

标签: android sqlite android-asynctask android-service intentservice


【解决方案1】:

您应该在应用程序和服务中仅使用 1 个 dbHelper 实例。在打开和执行关闭数据库时与同步语句协调。

【讨论】:

  • 你能给我举个例子吗?
猜你喜欢
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 2011-06-25
相关资源
最近更新 更多