启动IntentService多次android

时间:2013-08-20 13:24:15

标签: android intentservice

我正在开发一个Android项目,我正在尝试找到一种方法来改进以下代码。我需要知道我开发这个的方式是否合适:

  • 通知是从db
  • 中重新发送的GCM通知

我的问题是关于我多次打电话的意向服务。好吗?应该如何改进呢?

while (((notification)) != null)
{{
    message = notification.getNotificationMessage();
    //tokenize message
    if ( /*message 1*/) {
         Intent intent1= new Intent(getApplicationContext(),A.class);
         intent1.putExtra("message1",true);
         startService(intent1);
    } else
    {
         Intent intent2= new Intent(getApplicationContext(),A.class);
         intent2.putExtra("message2",true);
         startService(intent2);
    }
}
//retrieve next notification and delete the current one
}

1 个答案:

答案 0 :(得分:6)

IntentService旨在以异步方式在工作线程中运行。因此,如果需要,多次调用它没有错。意图将在一个线程中逐个运行。

我想你有一个派生自IntentService的类,并且它的onHandleIntent()被覆盖了。只有改进我可以看到你不需要创建两个单独的意图 - 它基本上是相同的意图,其中包含不同的额外内容。您可以在onHandleIntent()中区分这两个。

所以你的代码应该是这样的:

while (notification != null)
{
   Intent intent= new Intent(getApplicationContext(),A.class);
   message = notification.getNotificationMessage();

   if (msg1 condition) {
      intent.putExtra("message1",true);
   } else {
      intent.putExtra("message2",true);
   }

   startService(intent);

   //retrieve next notification and delete the current one
}