Communicate with bound Service Example

This post describes how to bind to a Service and unbind a Service on Button click.

Create your layout in activity_main.xml. Add a TextView for displaying date, a Button for binding to service, and another button for unbinding from Service, and a Button to update time.

<?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:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:textSize="25dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Service not bound"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:textSize="25dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="BIND SERVICE"
        android:layout_margin="10dp"
        android:id="@+id/button1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UNBIND SERVICE"
        android:layout_margin="10dp"
        android:id="@+id/button2"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Time"
        android:layout_margin="10dp"
        android:id="@+id/button3"/>

</LinearLayout>

Create a java file, TestService.java and add following code.

package com.example.dialog;

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

import androidx.annotation.Nullable;
import java.util.Date;

public class TestService extends Service {

    MyBinder binder1 = new MyBinder();

    public class MyBinder extends Binder{
        TestService getService(){
            return TestService.this;
        }
    }

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

    public void updateTime(){
        MainActivity.textView1.setText("Current Time: " + new Date());
    }
}

In AndroidManifest.xml add the Service class.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dialog">

    <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/Theme.Dialog">
        <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=".TestService"/>
    </application>

</manifest>

In MainActivity.java bind Service on button click.

package com.example.dialog;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    static TextView textView1;
    static TextView textView2;

    boolean bound;
    TestService service1;

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

        textView1 = findViewById(R.id.textView1);
        textView2 = findViewById(R.id.textView2);
        Button button1 = findViewById(R.id.button1);
        Button button2 = findViewById(R.id.button2);
        Button button3 = findViewById(R.id.button3);

        textView1.setText("Current Time: " + new Date());

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, TestService.class);
                bindService(intent, connection, BIND_AUTO_CREATE);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bound){
                    unbindService(connection);
                    bound=false;
                    textView2.setText("Service not bound");
                }
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bound) {
                    service1.updateTime();
                }
            }
        });

    }

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            TestService.MyBinder binder = (TestService.MyBinder) service;
            service1 = binder.getService();
            bound = true;
            textView2.setText("Service bound");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bound = false;
            textView2.setText("Service not bound");
        }
    };

}

Now run the app.

Leave a Reply