2011年9月7日 星期三

Android Service II



紀錄一下寫Service遇到的issue


在使用bindService()時,是一個Asynchronous的method,會觸發service的onBind


並且在activity得到一的binder的物件用以和service溝通


example:MyService.java



	public MyBinderClass mBinder=new MyBinderClass();

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}









所以之前code寫成這樣的時候 :(in myactivity.java)


private void setHomeServiceConnection(){
		serviceConn=new ServiceConnection(){

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// TODO Auto-generated method stub
				Log.d("HomeTab","onServiceConnected");
				hsBinder=(HomeService.MyBinderClass)service;
				serviceBind=true;
				
				hs=((HomeService.MyBinderClass)service).getMyService();
				hs.onStartCommand(null, 0, 0);
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				Log.d("HomeTab","onServiceDisconnected");
				serviceBind=false;
			}
			
		};
		getApplicationContext().bindService(new Intent(HomeTab.this,HomeService.class),serviceConn,Context.BIND_AUTO_CREATE);
		Log.d("HomeTab","After bind");
		hsBinder.testLog();//wrong!!!

最後一行就會出錯,原因是因為要等到onServiceConnected被觸發之後,


才能夠使用service由onBind回傳的binder,進一步使用binder裡面的method


所以這裡是用serviceBind variable來觀察是否和service連線


至於binder的寫法就是定義在service class,作為一個inner class


example:



public class MyBinderClass extends Binder{
        /** Communication between Activity and Service */
		
		public AppliancesInfo getAppInfo(){
			return appLastInfo;
		}
		
		public void SendCommand(String cmd){
			
		}
		
		public HomeService getMyService()
        {
        	return HomeService.this;
        }
		
		public void Testlog(){Log.d("123","123");}
    }






That's it.

沒有留言: