バックグラウンドサービスはブロードキャストによりUIを更新し、Activityはブロードキャストによりサービスを停止する


図のように動作します.
ボタンをクリックしてサービスを停止します.
Activityは次のとおりです.
package com.example.aandroidtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends PublicActivity {
	private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        text = (TextView) this.findViewById(R.id.textView1);
        
        // button, , service , service
        Button button = (Button) this.findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction("com.excample.stopService");
				sendBroadcast(intent);
			}
		});
        
        
        // , service , UI
        IntentFilter filter = new IntentFilter("com.example.updateUI");
        this.registerReceiver(new MyBroadCaseReceiver(), filter);
        
        // service
        Intent intent = new Intent(this, MyService.class);
        this.startService(intent);
    }
    
    class MyBroadCaseReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context arg0, Intent intent) {
			int i = intent.getIntExtra("data", 0);
			text.setText(String.valueOf(i));
		}
    }
}


サービスは次のとおりです.
package com.example.aandroidtest;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

public class MyService extends Service {
	boolean flag = true;// 

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

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// receiver, Activity , , service
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.excample.stopService");
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				flag = false;
				stopSelf();// service service
			}
		}, filter);
		
		// , 1s , Activity , UI
		new Thread(new MyThread()).start();
		
		return super.onStartCommand(intent, flags, startId);
	}

	class MyThread implements Runnable {
		int i = 100;
		public void run() {
			try {
				while(flag) {
					Thread.sleep(1000);
					
					Intent intent = new Intent("com.example.updateUI");
					intent.putExtra("data", i);
					sendBroadcast(intent);
					
					i++;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}