利用观察者模式实现Service与Activity的通信

public interface Subject{
	
	// 注册观察者对象
	public void attach(Observer observer);
	//删除观察者对象
	public void detach(Observer observer);
	//通知观察者
	public void nodifyObservers(String newState);
}

/**
 * 观察者接口
 * @author 超超boy
 *
 */
public interface Observer {
	
	void update(String str);
}
//service服务,模仿下载任务,每秒更新一下UI
import java.util.ArrayList;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class downService extends Service implements Subject {

	private List<Observer> list = new ArrayList<Observer>();
	private static downService downService;
	private int i=0;
	private boolean isStop;
	public downService() {
		System.out.println("实例化downService");
	}

	public void onCreate() {
        
		System.out.println("downService->onCreate");
		new Thread(new DownThread()).start();//启动线程
		super.onCreate();
	}
    /*//没用到    
	public void onRebind(Intent intent) {
		System.out.println("downService->onRebind");
		super.onRebind(intent);
	}*/
	//bindService时也不调用
	/*public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		System.out.println("downService->onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}*/
	//解绑
	public boolean onUnbind(Intent intent) {
		System.out.println("downService->onUnbind");
		isStop=true;
		return super.onUnbind(intent);
	}
	
	public void onDestroy() {
		super.onDestroy();
		System.out.println("downService->onDestroy");
	}
	//每个一秒发一个通知
    class DownThread implements Runnable{
         
		public void run() {
			while(!isStop){
				i++;
            try {
				Thread.sleep(1000);
				nodifyObservers("下载"+i+"");//发出通知,告诉观察者
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	 }
   }
    
    public boolean isStop() {
		return isStop;
	}
	public void setStop(boolean isStop) {
		this.isStop = isStop;
	}
	//注册观察者
	public void attach(Observer observer) {
		list.add(observer);
	}
    //删除观察者
	public void detach(Observer observer) {
		// TODO Auto-generated method stub
        list.remove(observer);
	}
	
    //发送消息给观察者
	public void nodifyObservers(String newState){
		System.out.println("size:"+list.size());
          for(Observer observer: list){
        	  observer.update(newState);
          }
	}
	public IBinder onBind(Intent intent) {
        System.out.println("onBind");
        
		return echoBinder;
   }
   private CountBinder echoBinder = new CountBinder();
	
    public class CountBinder extends Binder{
    	public downService getService(){
    		return downService.this;
    	}
    }
    public int getObserverSize(){
		return list.size();
	}
}
</pre><pre name="code" class="java"><span style="font-size:18px;">//这是Activity类,利用Handler异步更新UI</span>
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements Observer{

	Button registButton,unregistButton,changeButton,bindButton,unbindButton;
	TextView ceshiTextView;
	downService downService; //被观察者!
	private Intent intent;
	private MyHandler myHandler;
	downServiceConnection connection = new downServiceConnection();
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		initEvent();
	}
	
	private void initEvent() {
		//给service注册观察者
		registButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				downService.attach(MainActivity.this);
				System.out.println("观察者个数:"+downService.getObserverSize());
			}
		});
		//在service中删除观察者
		unregistButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				downService.detach(MainActivity.this);
			}
		});
		 //调用通知方法
		changeButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				downService.nodifyObservers("这是测试的");
			}
		});
		//绑定服务,即启动
		bindButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				//绑定服务!
				binddownService();
			}
		});
		//关闭服务
		unbindButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				MainActivity.this.unbindService(connection);
				unbinddownService();
			}
		});
	}
    private void binddownService(){
    	bindService(intent, connection, Context.BIND_AUTO_CREATE);
    } 
    private void unbinddownService(){
    	unbindService(connection);
    } 
	private void initView() {
		myHandler = new MyHandler();
		intent = new Intent(MainActivity.this, downService.class);  //描述跳转服务的intent
		registButton = (Button) findViewById(R.id.registButton);//注册观察者
		unregistButton = (Button) findViewById(R.id.unregistButton);//删除观察者
		changeButton = (Button) findViewById(R.id.changeButton);  //调用方法
		ceshiTextView = (TextView) findViewById(R.id.ceshiText);   
		bindButton = (Button) findViewById(R.id.qidongService_btn);  //绑定service
		unbindButton = (Button) findViewById(R.id.stopButton);   //解绑service
		
	}
	   //链接service
	   class downServiceConnection implements ServiceConnection{

				public void onServiceConnected(ComponentName name, IBinder service) {
					//得到service
					downService = ((downService.CountBinder) service).getService();
					downService.attach(MainActivity.this);  //注册观察者
					System.out.println("downServiceConnection..连接");
				}
		        //断开时调用的方法!
				public void onServiceDisconnected(ComponentName name) {
					System.out.println("service连接断开..");
				}
	}
	@Override
	public void update(String str) {
		//ceshiTextView.setText(str);
		Message message = myHandler.obtainMessage();
		Bundle data = new Bundle();
		data.putString("str", str);
		message.setData(data);
		message.sendToTarget();
		//System.out.println("不能更新UI?..");//不能在线程中直接更新UI
	}
	
	public class MyHandler extends Handler{     //Handler异步操作

		public void handleMessage(Message msg) {//异步更新UI
			Bundle bundle = msg.getData();
			String str = bundle.getString("str");
			ceshiTextView.setText(str);
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值