2

我正在设计一个 android 应用程序,它将收听传入的 SMS 并以特定方式处理它们。我有一个接收消息并将其发送到意图服务的广播接收器:

Intent serviceIntent = new Intent(context, SMSIntentService.class);
serviceIntent.putExtras(intent.getExtras());
context.startService(serviceIntent);

意图服务的目的是将 SMS 保存到我自己的数据库,然后通过 HTTP POST 将该消息发送到服务器,评估结果并更新应用程序的数据库并最终回复发送者。到目前为止一切都很好,但是由于有可能同时有很多 SMS 到达,我想将与服务器的通信解耦,将其放在另一个线程中。

所以到目前为止我正在做的是:

SmsDto sms = smsDataSource.saveSms(new SmsDto(originator, body, timestamp));

SMSProcessingTask task = new SMSProcessingTask(this.getApplicationContext(), sms);
Thread t = new Thread(task);
t.start();

到目前为止一切都很好,但我不相信这个有大量消息的实现。

所以,我的问题是:

在意图服务中,是否建议使用 ThreadPoolExecutor?我最终会得到这样的结果:

//in IntentService's onCreate
this.executor = Executors.newCachedThreadPool();

//in onHandleIntent()
executor.execute(task);

如果一段时间内没有收到消息并且 IntentService 停止,会发生什么情况。它创建的线程会继续运行吗?

我不知道这种方法是否是处理我想要完成的事情的最佳方式。

谢谢

更新:

  • 此应用程序中根本没有 UI 活动。
  • 由于与服务器的通信可能需要相当长的时间,我想尽量减少消息的处理时间,因此队列中的下一条短信被快速提取并开始处理。

4

2 回答 2

0

不,你不应该使用一个。主要原因是 SQlite 访问不是线程安全的,因此您不希望多个线程同时写入数据库。此外,如果您的任务碰巧更新了 UI,它就不会那样工作。

我真的不明白您为什么要执行这些任务: IntentService 已经从 UI 线程处理了它的消息。

于 2012-08-23T15:40:37.823 回答
0

您可以做的是使用 submit(Callable) 方法而不是 execute 方法。

这样你就可以得到一个带有你想在数据库中写入的数据的未来对象,并且没有线程会真正接触它,因为它不像 Phillippe 所说的那样安全

当我需要发送多个 httprquests 时,我以类似的方式使用它。我使用 SQL DB 管理它们,因此只在 onHandleIntent 上进行写入。

while(helper.requestsExists()){
        ArrayList<String> requestArr = helper.getRequestsToExcute(3);
        //checks if the DB requests exists
        if(!requestArr.isEmpty()){
            //execute them and delete the DB entry
            for(int i=0;i<requestArr.size();i++){
                file = new File(requestArr.get(i));
                Log.e("file",file.toString());
                Future<String> future = executor.submit(new MyThread(file,getApplicationContext()));

                Log.e("future object", future.toString());
                try {
                    long idToDelete = Long.parseLong(future.get());
                    Log.e("THREAD ANSWER", future.get() + "");
                    helper.deleteRequest(idToDelete);
                } catch (InterruptedException e) {
                    Log.e("future try", "");
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    executor.shutdown();

其次,在 onHandleIntent 完成之前,intentService 不会停止,即使这样,线程也会继续运行,直到完成工作

于 2015-05-27T13:09:30.567 回答