Tuesday 25 June 2013

How to create Service in Android




What is Service?
                A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them.
Declaring a service in the manifest
                To declare your service, add a <service> element as a child of the <application> element. For example:

              
              <manifest ... >
                                <application ... >
                                                <service
                                                android:name=".DetectService"
                                                android:enabled="true"
                                                android:exported="false" >
                                                 </service>
                                </application>
                </manifest>
you can ensure that your service is private to your application only if you include the android:exported attribute and set it to "false".
Creating a Service
                A started service is one that another component starts by calling startService(), resulting in a call to the service's onStartCommand() method and the  component can stop it by calling stopService().
An application component such as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.

Here is the code for Extending the Service class.


public class DetectService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    int res = super.onStartCommand(intent, flags, startId);
        Toast.makeText(getApplicationContext(),"Service Started",Toast.LENGTH_LONG).show();
        return res;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"Service Stopped",Toast.LENGTH_LONG).show();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}



We can call the service in button event like :


public class MainActivity extends Activity {
    Button startButton;
    Button stopButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startButton=(Button)findViewById(R.id.StartButton);
        stopButton=(Button)findViewById(R.id.StopButton);
    }
    public void Start(View view)
    {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
        Option(true);
    }
    public void Stop(View view)
    {
        Option(false);
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
    }
    private void Option(boolean enable)
    {
        Intent intent = new Intent(this, DetectService.class);
        if(enable)
        {
            startService(intent);
        }
        else
        {
            stopService(intent);
        }
    }
    @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;
    }
}




Here is the activity_main.xml:
 
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Service"
        android:id="@+id/textView"/>
    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start"
            android:id="@+id/StartButton"
            android:layout_marginTop="30dp"
            android:layout_below="@+id/textView"
            android:layout_toLeftOf="@+id/StopButton"
            android:onClick="Start"/>
    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stop"
            android:id="@+id/StopButton"
            android:layout_alignTop="@+id/StartButton"
            android:layout_centerHorizontal="true"
            android:onClick="Stop"/>



A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. So, the service must stop itself by calling stopSelf() or another component can stop it by calling stopService().


No comments:

Post a Comment