1、Activity:
import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; public class DemoActivity extends Activity { /** Called when the activity is first created. */ private Intent intent ; private MyServiceConnection conn; private IService ibinder; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); intent = new Intent(this,MyService.class); conn = new MyServiceConnection(); } /** * 希望一个服务一直存在,并且能够调用服务里面的方法。 * 启动服务 * 先通过startService()的方式来启动服务,再通过onBind()的方式去绑定服务。 * * onCreate() --> onStart() -->onBind() * * * 停止服务: * 1: 先unbindService()来解绑服务,再通过stopService()来停止服务 * onUnbind() ---> onDestory() * * 2:先stopService()来停止服务,再通过unbindService()来解绑服务 * * onUnbind() ---> onDestory() * * * 通过startService()方式启动的服务,必须通过调用stopService()才能停止服务。 * 如果服务还有绑定对象,那么一个服务是不会被停止的。 * * * 怎么去调用服务里面方法。1 必须通过bindService()才能和服务进行通讯。打开了一个ServiceConnection连接。服务给我们返回了一个IBinder对象 */ public void startservice(View v){ startService(intent); } public void stopservice(View v){ stopService(intent); } /** * 一个访问者只能和服务绑定一次,多次绑定那么服务里面的onBind()方法不会多次被调用 */ public void bindservice(View v){ bindService(intent, conn, BIND_AUTO_CREATE); } /** * 一旦访问者和服务断开了连接,如果再次解绑服务,会出现异常 */ public void unbindservice(View v){ unbindService(conn); } private final class MyServiceConnection implements ServiceConnection{ public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub ibinder = (IService) service; } public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } } public void call(View v){ ibinder.invoke(); } }
2、MyService
import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class MyService extends Service { private IBinder ibinder = new MyBinder(); @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.i("i", " onCreate()"); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); Log.i("i", " onStart()"); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.i("i", " onBind()"); return ibinder; } @Override public boolean onUnbind(Intent intent) { // TODO Auto-generated method stub Log.i("i", " onUnbind()"); return super.onUnbind(intent); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Log.i("i", " onDestroy()"); } private final class MyBinder extends Binder implements IService{ public void invoke() { // TODO Auto-generated method stub callme(); } } private void callme(){ Log.i("i", "服务里面的方式被调用了"); } }
3、IService
public interface IService { public void invoke(); }
4、最后别忘了在AndroidManifest.xml中注册上Service