Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active November 4, 2025 13:11
Show Gist options
  • Select an option

  • Save sunmeat/eaecf4682411cbfb221610a6f00330ba to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/eaecf4682411cbfb221610a6f00330ba to your computer and use it in GitHub Desktop.
bind service android example
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#FF3333"
android:onClick="start"
android:text="Підключити сервіс!"
android:textAllCaps="false" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#FF8833"
android:onClick="stop"
android:text="Відключити сервіс!"
android:textAllCaps="false" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#FFFF33"
android:onClick="faster"
android:text="Логування швидше!"
android:textAllCaps="false" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#33AA33"
android:onClick="slower"
android:text="Логування повільніше!"
android:textAllCaps="false" />
</LinearLayout>
=============================================================
MainActivity.java:
package com.sunmeat.services;
import android.content.*;
import android.os.*;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
final String LOG_TAG = "service_logs";
boolean bound = false;
ServiceConnection sConn;
Intent intent;
long interval;
MyService service;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, MyService.class);
sConn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.i(LOG_TAG, "MainActivity onServiceConnected");
service = ((MyService.MyBinder) binder).getService();
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
// система Android викликає цей метод у разі непередбаченої втрати
// підключення до сервісу, наприклад, при збої в роботі сервісу або у випадку
// Його завершення. цей метод не викликається, коли клієнт скасовує прив'язку
Log.i(LOG_TAG, "MainActivity onServiceDisconnected");
bound = false;
}
};
}
public void start(View v) {
// BIND_AUTO_CREATE - створити сервіс, якщо він ще не виконується
bindService(intent, sConn, BIND_AUTO_CREATE);
}
public void stop(View v) {
if (!bound) return;
unbindService(sConn);
bound = false;
}
public void faster(View v) {
if (!bound) return;
interval = service.downInterval();
Objects.requireNonNull(getSupportActionBar()).setTitle("interval = " + interval);
}
public void slower(View v) {
if (!bound) return;
interval = service.upInterval();
Objects.requireNonNull(getSupportActionBar()).setTitle("interval = " + interval);
}
}
====================================================================================
MyService.java:
package com.sunmeat.services;
import android.app.Service;
import android.content.Intent;
import android.os.*;
import android.util.Log;
public class MyService extends Service {
final String LOG_TAG = "service_logs";
MyBinder binder = new MyBinder();
long interval = 1000;
Handler h;
Runnable r;
int counter = 0;
public void onCreate() {
super.onCreate();
Log.i(LOG_TAG, "MyService onCreate");
h = new Handler(Looper.getMainLooper());
r = new Runnable() {
@Override
public void run() {
counter++;
Log.i(LOG_TAG, counter + "");
h.postDelayed(this, interval);
}
};
h.postDelayed(r, interval);
}
long upInterval() {
interval = interval + (long) 100;
return interval;
}
long downInterval() {
interval = interval - (long) 100;
if (interval < 100) interval = 100;
return interval;
}
public IBinder onBind(Intent intent) {
Log.i(LOG_TAG, "MyService onBind");
return binder;
}
class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
// коли виконується скасування прив'язки служби до всіх клієнтів, система Android знищує таку
// службу (якщо вона була запущена разом з onStartCommand())
public boolean onUnbind(Intent intent) {
Log.i(LOG_TAG, "MyService onUnbind");
return true;
}
public void onDestroy() {
super.onDestroy();
h.removeCallbacks(r);
Log.i(LOG_TAG, "MyService onDestroy");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment