Thursday, 19 December 2013


How to start and stop service in android.


Here we see how to start and stop a service dynamically.


What is Service ?


A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the lifecycle of an activity. 

As there are two methods by which we start and stop service  :
  1. startService (Intent service)
  2. stopService (Intent service)

In order to start a service we need to call a method name onStartCommand(Intent intent, int flags, int startId) and to stop a service call a method name onDestroy() . All this work we do in class which extends Service class.

Create a project with the following details :

·         ProjectName: StartStopServicee
·         PackageNamesat.tuts4mobile.startstop
·         ActivityNameMainActivity

In the MainActivity.java file, copy the following code :

package sat.tuts4mobile.startstop;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);

                        Button start = (Button) findViewById(R.id.button1);
                        start.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                startService(new Intent(MainActivity.this, MyService.class));
                                    }
                        });

                        Button stop = (Button) findViewById(R.id.button2);
                        stop.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                stopService(new Intent(MainActivity.this, MyService.class));
                                    }
                        });

            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                        // Inflate the menu; this adds items to the action bar if it is present.
                        getMenuInflater().inflate(R.menu.main, menu);
                        return true;
            }

}

Create a new class name MyService.java file, copy the following code :

package sat.tuts4mobile.startstop;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service{

            @Override
            public IBinder onBind(Intent intent) {
                        // TODO Auto-generated method stub
                        return null;
            }
           
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            // TODO Auto-generated method stub
           
                        Toast.makeText(MyService.this, "Service Started!!!", Toast.LENGTH_SHORT).show();

            return super.onStartCommand(intent, flags, startId);
    }
   
    @Override
    public void onDestroy() {
            // TODO Auto-generated method stub
           
                        Toast.makeText(MyService.this, "Service Stoped!!!", Toast.LENGTH_SHORT).show();

            super.onDestroy();
    }

}

In the activity_main.xml file, copy 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Start Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="20dp"
        android:text="Stop Service" />

</RelativeLayout>

In the 
AndroidMainfest.xml file, copy the following code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sat.tuts4mobile.startstop"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sat.tuts4mobile.startstop.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <service android:name="sat.tuts4mobile.startstop.MyService"></service>
       
    </application>

</manifest>

Click this to download source code

When you run the application , you see the following screens :





17 comments:

  1. Excellent information, thanks for sharing great information. We deal with Facebook Applications Development this information is quite informative and interesting.

    ReplyDelete
  2. Great resources’ really appreciate for posting such a great Blog.
    android

    ReplyDelete
  3. Portable provisions can't simply just fun you yet even it can supporting your organization prerequisites by permitting you join with your work at whatever time, anyplace. Abroad versatile database joining results in going with a portable computer incorporate the era, supply, taking care of, and enlargement of requisitions. Cell program creators, outline provisions for web fueled portable mechanism, which incorporate Cellular Devices, Individual electronic staff and Business electronic staff. See more at:.....
    iPhone application development // Andriod application
    development
    // mobile application development

    ReplyDelete
  4. I like ipad is a multipurpose mechanism. It is for stimulation as well as it has functionalities to serve as a helpful unit for business. You can complete numerous operations of business with ipad. It has all functionalities like iphone aside from you can not make a call. Today we will see some functional requisitions for business.Android application development // Android
    application development
    // mobile app developers

    ReplyDelete
  5. This is really very helpful. Thanks for sharing. TechTrendsIT, is a leading Mobile Application Development Company.

    ReplyDelete
  6. Nice blog! I loved reading through your blog. wish you good luck for your best efforts...
    -----------------------------------------------------------------------------
    Mobile App Cross Platform Development && Hire Php Developer India

    ReplyDelete
  7. Wow amazing. I really appreciate your this work hard such a great informative post to developers for android app development I would like to pay thanks to you

    ReplyDelete
  8. This blog is very helpful for the begginers, thanks for sharing it with such a easy langugae. In today's time Mobile Application and Android Application Development is new and good technologies.

    ReplyDelete
  9. I have been searching for various blog for getting knowledge in mobile apps development. This blog is very easy to understand. Thanks for sharing this blog.href="http://www.balladonia.com"moblile application application

    ReplyDelete
  10. Nice Post!! I Really enjoyed to read your post with such a nice information. Its very helpful for me Thanks for sharing this information....!!!

    ReplyDelete
  11. Wow, awesome ! I really appreciate your this work had such a great informative post with developers for android app development, I would like to pay thanks to you.

    ReplyDelete
  12. This comment has been removed by a blog administrator.

    ReplyDelete
  13. its an amazing post, count me as your regular visitor, I would love to read more of your post about free mobile messaging app update

    ReplyDelete
  14. Excellent information, Great post here. I found that you shared a complete information on Android Apps Development. OnGraph Technologies provide Android App development services and other Mobile app development services.

    ReplyDelete
  15. Really Great Information, Thanks for the post you have provided step by step process so anyone can understand. If are you looking best Mobile application development company in india. For understanding Mobile Application Development and Android Application Development.

    ReplyDelete
  16. Really nice information. I was searching for that code.
    android app developer

    ReplyDelete