Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Services in Android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 171
    Comment on it

    A service is a component that runs in the background without user interaction and with no user interface.
    Services performs long running tasks without being visible like, playing music, triggering notifications etc.
    Services has two forms:-

     

    1) Started Service :-  A service is called started service when an application component (like activity) starts the service by calling "StartService()" .
    Once Started a service runs indefinitely , even if the starting component gets destroyed.

    LifeCycle of a Started Service:-

    StartService()  ->  onCreate()  ->  onStart()  ->  onDestroy()

     

     


     2) Bound Service :- A service is called a "bound service" when an application component binds to it by calling bindService().

    LifeCycle of a Bound service:-

    StartService()  ->  onCreate()  ->  onBind()  ->  onUnBind()  -> onDestroy()
        

     

    Here is the simple example that makes you more clear about the services:-

    Step :-1 create a service class:-

    public class MyServiceOne extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            System.out.println("On Bind");
            return null;
        }
        @Override
        public void onStart(Intent intent, int startId) {
          super.onStart(intent, startId);
          String msg = intent.getStringExtra("MSG");
          System.out.println("Message is- "+ "On Service start(),I got msg "+msg);
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
                System.out.println("On Destroy");
        }

     

     

    Step 2:- Create a MainActivity that call the service and code the below lines to call the service

    Intent intent=new Intent(this,MyServiceOne.class);
    intent.putExtra("MSG","Mesaage started from Main activity");
    startService(intent);

     

    Step 3:- You must declare a service in manifest:-

    <service android:name=".MyServiceOne"/>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: