Friday, March 29, 2013

How to Create Services in Android : Services demo in Android : Service Example : Background Services

Hello friends,
      Today I am going to share my R & D on Services in Android. A Service is a component that can run in the background for an arbitrary amount of time. As with the activity tag, you can optionally include one or more <intent-filter> elements that the service supports or <meta-data> values; see the activity's <intent-filter> and <meta-data> descriptions for more information.

Services Life cycle is totally differences to Activity life cycle. Copy below given code and test it yourself-

Screen Shot:



1)Create new android demo project.
2)Create MyService.java class.
3)Create  ServiceDemo.java activity.
4)And for testing Create a new activity NextPage.java
5)Create a raw folder inside your res folder and put a .mp3 file/song into raw folder.
6)Create main.xml
7)Create next.xml
8)Add Services in manifest.xml-

 <service
            android:name=".MyService"
            android:enabled="true" />

My Code-

1)Myservice.java

package com.example.seevicedemoaudioplayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
private static final String TAG = "My Service Demo";
MediaPlayer myPlayer;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");

myPlayer = MediaPlayer.create(this, R.raw.loveme);
myPlayer.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
myPlayer.stop();
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
myPlayer.start();
}
}

2)ServicesDemo.java

package com.example.seevicedemoaudioplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop,buttonNext;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonNext = (Button) findViewById(R.id.buttonNext);

buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
buttonNext.setOnClickListener(this);
}

public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
case R.id.buttonNext:
Log.d(TAG, "onClick: next Page");
Intent intent=new Intent(this,NextPage.class);
startActivity(intent);
break;
}
}
}

3)NextPage.java

package com.example.seevicedemoaudioplayer;

import android.app.Activity;
import android.os.Bundle;

public class NextPage extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);

}
}

4)main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="20dp"
        android:text="Services Demo"
        android:textColor="#ffffff"
        android:textSize="20sp" />

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" >
    </Button>

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop" >
    </Button>

    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next Page" >
    </Button>

</LinearLayout>

5)next.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="169dp"
        android:text="Welcome- Second page"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ffffff" />

</RelativeLayout>

7)AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.seevicedemoaudioplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ServicesDemo"
            android:label="@string/title_activity_service_demo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true" />
         <activity
            android:name=".NextPage"/>
    </application>

</manifest>

8)Most Important Create raw folder inside res and put a .mp3 file like-loveme.mp3

Download Zip Code

Thank you so much!
Your comments awaited...
:);







15 comments :

  1. like your all tutorial this is also awesome.

    ReplyDelete
  2. Hi,

    Nice example, but is there any way to design service without UI and that service need to communicate with local DB or webservice, if any example please let me know.

    thanks

    ReplyDelete
    Replies
    1. Hi I don't have any demo for save data into database using services. But if you need any thing like that same code will work for you. If you don't want this UI change with yours and start service onCreate() method of application and if you want you can stop it onDestroy() method.

      Delete
  3. hello sir,
    I have developed an application in android.
    could you please help me with adding a background service that uses the internet and runs in the background of my app, basically fetch and write data to the internet in background
    thank you
    my emailid incase u need : mohitgodiya@gmail.com
    mohit

    ReplyDelete
    Replies
    1. Hi Mohit, As you can see above code for play music in background, that's mean this services is working so now just modify according your requirement.

      1)Write a method for getting data from server using web-services.
      2)Write Broadcast-Receiver for update your UI with exciting data from server.
      3)Call that method inside your services inside onCreate()method.

      Delete
  4. Replies
    1. Okay I will upload on git server, I will inform you. If you are in hurry you can copy paste from above for now :)
      Thanks!

      Delete
    2. Hi,
      you can download zip code from above "Download Link " on my blog..

      Thanks!

      Delete
  5. hi manish
    how to update the server for ever 5mins without UI i,e in the background process

    ReplyDelete
    Replies
    1. You can use Alarm Manager for this check below article-
      http://www.androidhub4you.com/2013/12/android-alarm-manager-example-how-to.html

      Delete
    2. This comment has been removed by the author.

      Delete
    3. yes i saw your link it was quiet helpful but i got lot of doubht in that ,it seems like in broadcast receiver we are not allowed to do long process like updating the server for every 5 mins . So i guess it has to be done through service method from broadcast receiver .i,e broadcast receiver is fired for every 5 mins from alarm manager and once it get fired service method should be called from the receiver method . am i right Manish?? if im correct then how to call the service method from receiver method , Because i don't have any idea about the service method please help me desperately needed answer ..


      Delete
    4. No you are wrong Broadcast receiver is not doing anything here. You have to call your query inside doInBackground method or use Service. And Alarm manager will send data every after 5 min or what time you want.

      Broadcast is only used for any notification like getting wifi network revive any message etc. Well if you have any doubt I will suggest first read and understand things then only code.

      Delete
  6. This comment has been removed by the author.

    ReplyDelete

Note: Only a member of this blog may post a comment.