android 将Service绑定到Activity

Service可以和Activity绑定,后者会维持对Service实例的引用,此引用允许你像对待其他实例化的那样,对正在运行的Service进行方法调用。

允许Service和Activity绑定,这样能够获得更加详细的接口。要让一个Service支持绑定,需要实现onBind方法,并返回被绑定Service的当前实例。

package com.example.androidtest.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
	private final IBinder binder = new MyBinder();
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return  binder;
	}
	
	public class MyBinder extends Binder{
		MyService getService(){
			return MyService.this;
		}
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	
}

Service和其他组件之间的连接表示为一个ServiceConnection.

要想将一个Service和其他组件进行绑定,需要实现一个新的ServiceConnection,建立一个连接之后,就可以通过重写onServiceConnected和onServiceDisconnectd方法来获得对service的引用。程序:

package com.example.androidtest;

import com.example.androidtest.service.MyService;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;

public class MainActivity extends Activity {
	private MyService myService;
	//service和activity之间的连接
	private ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			// TODO Auto-generated method stub
			myService = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			//当建立连接时调用
			myService = ((MyService.MyBinder)service).getService();
			
		}
	};
	
	public void toBind(){
		//绑定一个service
		Intent bindIntent = new Intent(MainActivity.this,MyService.class);
		bindService(bindIntent, mConnection, BIND_AUTO_CREATE);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



android 将Service绑定到Activity,布布扣,bubuko.com

android 将Service绑定到Activity

上一篇:spring cloud配置中心属性加密处理


下一篇:Pyhon之Django中的Form组件