Android TutorialsImplementing Simple Service in Android

Implementing Simple Service in Android

In this tutorial we are going to implement a Simple Service which we have to start and stop.

  • In this implementation of Service which will calculate the average of the series of number’s that we will enter in the text field.
  • Steps are as Follows:
  1. Create a new project , your MainActivity.java and activity_main.xml files will be created.
  2. In the activity_main.xml file take a Large Text from the Palette.
  3. Also take the Plain Text from the Text Fields and two buttons in the activity_Main.xml file.
  4. Set the button property as : android:text=”Stop Service”.
  5. And for another button set as : android:text=”Average”.
  6. So now the text of the buttons are set as Stop Service and Average .
  7. Now set the text in the text property of the TextView.
  8. For example : android:text=”Enter Numbers ,Space Seperated”.
  9. So Now your activity_main file’s Graphical Layout will look like this :
  10. 1

  11. Now go to your MainActivity.java file .
  12. In this declare the following in the MainACtivity class as :
    1. Private EditText numbersText ;
    2. Private static Intent averagingIntent ;

  13. Now in the onCreate( ) method insert the following code :
    numbersText = (EditText) findViewById(R.id.editNumbers);
  14. So the MainActivity.java file will look for the EditText by finding it by its id.
  15. So the MainActivity.java file will look like this :
  16. 2

  17. Now write the following code for Average button in the MainActivity.java file as shown below :
  18. [code language=”java”]public void startService(View v)
    {
    String[] strNumbers = numbersText .getText().toString().split(" ");
    int[] numbers = new int[strNumbers.length];
    for(int i=0;i<=strNumbers.length;i++)
    {
    numbers[i]=Integer.parseInt(strNumbers[i]);
    }

    averagingIntent = new Intent(MainActivity.this,TestService.class);
    averagingIntent.putExtra("numbers", numbers);
    startService(averagingIntent);
    }

    [/code]

  19. Now startService is the name given to the onClick property of the Average button.
  20. Let’s see the explanation of the code line by line :
    1. startService gets a String array of numbers from the numbersText,getting its text ( ) ,converting it to string( ) and then splitting it on the space character.
    2. Here we take the string array and convert it to the integer array by doing new int and the [strNumbers.length].
    3. We take a for loop to set the integer array to the numbers entered by the user .
    4. Now set up the intent by using the calling class and the target class and startService with the intent.

  21. Then stop the service.
  22. So now you will have the following code :
  23. 3

  24. Now take another java class for example: TestService.java
  25. Class TestService must be extended with Service .
  26. In this write the oncreate( ) method which must be called through super.
  27. [code language=”java”]public void onCreate()
    {
    super.onCreate();
    }
    [/code]

  28. The next method important here is the onStartCommand this is where the intent enters into the service.
  29. [code language=”java”]public int onstartCommand(Intent intent,int flags, int startId)
    {
    int[] numArray = intent.getExtras().getIntArray("numbers");
    float avg = findAverage(numArray);
    Toast.makeText(getApplicationContext(), String.format("Average : %f", avg), Toast.LENGTH_SHORT).show();

    return startId;

    }
    [/code]

  30. Here we get the numeric array an integer array by getting those extras with that number array.
  31. Then the avg is the calculated average that is calculated by the “ find average logic” .
  32. Toast is used to display the message of the calculated average.
  33. Then return the start Id.
  34. Also call the onDestroy( ) method to stop the service .
  35. Write down the logic for the calculation of average.
  36. [code language=”java”]float findAverage(int[]nums)
    {
    int sum=0;
    for(int i=0;i<=nums.length;i++)
    {
    sum += nums[i];
    }
    return(float)sum/nums.length;
    }

    [/code]

  37. So your window will look as shown below :
  38. 4

  39. Now in the android manifest file list the service as stated
  40. [code language=”xml”]<service
    android:name=".TestService">
    </service>
    [/code]

  41. Now run your app.
  42. You will get the following display :
  43. 4

  44. Now enter the numbers and click on the Average button :
  45. 5

  46. Thus a Tost message will display the calculated average :
  47. 6

  48. Now click on the Stop Service button to stop the service
  49. 7

  50. Thus we have implemented a Normal Service in Android

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -