BoundService.java
Dosyayı İndir
package com.godoro.androiddevices;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class BoundService extends Service {
private boolean serviceRunning;
private final static long SERVICE_STEP_INTERVAL=5000;
private final static long SERVICE_COUNT_MAX=10;
private long serviceCount;
private Handler handler=new Handler();
private String content = "İçerik verisi burada.";
private Binder binder = new BoundBinder();
public String getContent() {
return content+" "+serviceCount;
}
@Override
public void onCreate() {
super.onCreate();
work();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class BoundBinder extends Binder {
public BoundService getService() {
return BoundService.this;
}
}
private void work(){
workBefore();
Runnable runnable=new Runnable() {
@Override
public void run() {
while(serviceRunning){
workStep();
}
workAfter();
}
};
Thread thread=new Thread(runnable);
thread.start();
}
private void workBefore(){
serviceRunning=true;
serviceCount=0;
String message=String.format("Hizmet %d. kez çalıştı",serviceCount);
showToast("Hizmet başladı");
}
private void workStep(){
try {
Thread.sleep(SERVICE_STEP_INTERVAL);
String message=String.format("Hizmet %d. kez çalıştı",serviceCount);
showToast(message);
serviceCount++;
if(serviceCount==SERVICE_COUNT_MAX){
serviceRunning=false;
}
}catch (Exception e){
Log.e("GodoroAndroid", "Hizmet hatası", e);
}
}
private void workAfter(){
showToast("Hizmet bitti");
}
private void showToast(final String message){
Runnable action=new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
};
handler.post(action);
}
}
Dosyayı İndir