Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start IntentService multiple times android

I am working on an android project and I am trying to find a way to improve the following code . I need to know if the way I developed this is ok or not:

  • notification is a GCM notification that is retrived from a db

My question is about the intent service that I am calling several times. Is it ok? How should improve this?

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
}
like image 802
just ME Avatar asked Aug 20 '13 13:08

just ME


1 Answers

IntentService is meant to be used in asynchronously to run in a worker thread. So nothing is wrong to call it multiple times if required. The intents will be running one by one in a thread.

I suppose you have a class derived from IntentService and its onHandleIntent() overridden. Only improvement I can see that you don't need to create two separate intents - it's basically same intent with different extras in it. You can differentiate these two in onHandleIntent().

So your code should look like:

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
}
like image 112
sjdutta Avatar answered Oct 22 '22 10:10

sjdutta