Introduction
In this article I will describe services in Android. A service is an application component that is run in the background without user interaction. If we want to add a service to our application then we must add a declaration in the "AndroidManifest.xml" file and the service class must be extended. In this article, I will tell you how to play music in the background using a service. In this article, I took a MP3 song file that must play using a service in the app.
Step 1
As usual first of all create a new project as "File" -> "New" -> "Android application Project".

Step 2
After that, import an audio file; I imported a MP3 file in my app as shown in the following image.

Step 3
Now open the "actiivity_main.xml" file and update it with the following code:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity"
- android:background="#0ff0ff" >
- <TextView
- android:id="@+id/song"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:layout_alignParentRight="true"
- android:layout_marginBottom="208dp"
- android:background="#f00f00"
- android:gravity="center"
- android:textSize="40sp"
- android:text="@string/play"
- android:textColor="#00f00f" />
- </RelativeLayout>
Step 4
Now open the "MainActivity.java" file and update it with the following code.
- package com.demo.service;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.TextView;
- public class MainActivity extends Activity {
- Intent intent;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- final TextView tv= (TextView) findViewById(R.id.song);
- intent=new Intent(this,MyService.class);
- tv.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- tv.setText(R.string.playsongs);
- startService(intent);
- }
- });
- }
- @Override
- protected void onPause() {
- // TODO Auto-generated method stub
- stopService(intent);
- super.onPause();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }



Join the conversation! Your thoughts help the community grow.