Post Top Ad

Post Top Ad

Saturday 29 April 2017

#What are services Bind & Unbind Services




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.
Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.
Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them. Services can also be configured to be restarted if they get terminated by the Android system once sufficient system resources are available again.
It is possible to assign services the same priority as foreground activities. In this case it is required to have a visible notification active for the related service.

Services for Asynchronous Execution

There are a couple of benefits of using Services (with Threads ofcourse) for background operations over using regular threads in say an Activity or a Broadcast Receiver.
  • When a process is terminated by the runtime, that’ll terminate all the background threads which won’t restart by default whereas a Service maybe restarted on termination by the system. Also the runtime terminates processes based on their importance where a Service process has more importance than the regular threads.
  • Activity and BroadcastReceiver are decoupled from the threads that they spawn whereas a Service can couple with the Threads it creates and end its lifecycle when the background task is done using stopSelf() for instance.

Local and Remote Service

Components start a Service through intents. These components are also referred to as client components sometimes. Now this invocation can happen in three ways:
  • Local Service – Both the component and Service of the application runs in the same process.
  • Private Remote Service – The Service runs in a different process from the component but only accessible to components that belongs to only that particular application.
  • Global Remote Service – Pretty much similar to Private Remote Services but also accessible to other applications, not through the class name (as they won’t know it) but through Intent Filters.
For remote services, the separate process has its own main thread which doesn’t delay the execution of the UI threads of the client components.
Services can be of two types – Started and Bound.

Understanding Bound Services

In common with started services, bound services are provided to allow applications to perform tasks in the background. Unlike started services, however, multiple client components may bind to a bound service and, once bound, interact with that service using a variety of different mechanisms.

Bound services are created as sub-classes of the Android Service class and must, at a minimum, implement the onBind() method. Client components bind to a service via a call to the bindService() method. The first bind request to a bound service will result in a call to that service’s onBind() method (subsequent bind request do not trigger an onBind() call). Clients wishing to bind to a service must also implement a ServiceConnection subclass containing onServiceConnected() and onServiceDisconnected() methods which will be called once the client-server connection has been established or disconnected respectively. In the case of the onServiceConnected() method, this will be passed an IBinder object containing the information needed by the client to interact with the service. 

Create New Projects:
BindService\app\src\main\res\layout
   1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.smartpropertyhunt.tanuj.bindservice.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind Service"
        android:onClick="bindToService"
        android:id="@+id/button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Unbind Service"
        android:onClick="unBindFromService"
        android:id="@+id/button2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Result"
        android:id="@+id/button3"
        android:onClick="getResult"
        android:layout_above="@+id/button" />
</LinearLayout>

BindService\app\src\main\java\com\smartpropertyhunt\tanuj\bindservice 

2.MainActivity.java:
 package com.problemhunt.tanuj.bindservice;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ServiceConnection mServiceConnection;
    private MyService mMyService;
    private boolean isServiceConnected;

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

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                mMyService = ((MyService.LocalService) iBinder).getService();
                isServiceConnected = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
    }

    public void bindToService(View view) {
        if (isServiceConnected) {
            Toast.makeText(MainActivity.this, "Service is connected already",
                    Toast.LENGTH_LONG).show();

        } else {
            Intent intent = new Intent(MainActivity.this, MyService.class);

            bindService(intent,mServiceConnection, BIND_AUTO_CREATE);
        }
    }
    public void unBindFromService(View view) {
        if (isServiceConnected){
            unbindService(mServiceConnection);
            isServiceConnected=false;
        }else{
            Toast.makeText(MainActivity.this, "Service is not connected",
                    Toast.LENGTH_LONG).show();

        }
    }

    public void getResult(View view) {
        if (isServiceConnected) {
            int result = mMyService.doMultiply(20, 35);
            Toast.makeText(MainActivity.this, String.valueOf(result),
                    Toast.LENGTH_LONG).show();

        } else {
            Toast.makeText(MainActivity.this, "Service is not connected",
                    Toast.LENGTH_LONG).show();
        }

    }
}
BindService\app\src\main\java\com\smartpropertyhunt\tanuj\bindservice 
3. MyService.java
 package com.problemhunt.tanuj.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    public MyService() {

    }
    IBinder myBinder=new LocalService();

    public int doMultiply(int i, int i1) {
        return i*i1;
    }

    class LocalService extends Binder{
        public  MyService getService(){
            return  MyService.this;

        }

    }

    @Override
    public IBinder onBind(Intent intent) {

        return myBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService semwal","onCreate");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("MyService semwal","onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.i("MyService semwal", "onRebind");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("MyService semwal", "onCreate");
    }
}


 
 

No comments:

Post a Comment