Tuesday, 6 February 2018

How to create a service in android

What is Service

Service is a component which run in background to perform long term operations. Service has no user interface.As service has no user interface it is not bound to life cycle of Activity.
Services are used for repetitive and potentially long operations. Internet downloads, checking for new data, data processing, updating content providers and the like.
In this tutorial we'll learn how to create and implement a service.

1. Create Service Class
Create a class named ServiceTest.java and use below code. It has to extends Service Class or one of it's child class.
ServiceTest.java
package com.example.servicetutorial;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/** * Created by Vishnu Kumar Soni on 2/6/2018. */
public class Servicetest extends Service{

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

    @Override
    public int onStartCommand(Intent intent, 
        int flags, int startId) {
        Toast.makeText(getApplicationContext(),
        "Service Started",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override    public void onDestroy() {
    Toast.makeText(getApplicationContext(),
    "Service Stopped",Toast.LENGTH_LONG).show();

    }
}

2. Declaring Service In Manifest
It is must to declare Service class in Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicetutorial">
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
<service
            android:name=".Servicetest"
            android:label="TextService">
        </service>
</application>

</manifest>
3. Creating Main Activity
Do the following changes in activity_main.xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.servicetutorial.MainActivity"
    android:orientation="vertical"    android:gravity="center">

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"/>
    <Button
        android:id="@+id/end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="End Service"/>
</LinearLayout>


Now open MainActivity.java and do the following chages.
MainActivity.java
package com.example.servicetutorial;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        Button buttonStart = (Button)findViewById(R.id.start);
        Button buttonend = (Button)findViewById(R.id.end);
        buttonend.setOnClickListener(this);
        buttonStart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(context,Servicetest.class);
        if(v.getId()==R.id.start)
        {
            startService(intent);
        }else if(v.getId() ==R.id.end){
            stopService(intent);
        }

    }
}

No comments:

Post a Comment