android调用当地服务示例

android调用本地服务示例

在大多数情况下android只需要调用本地的服务(也就是和调用者在同一个进程的服务)就可以,调用服务必须采用的绑定的方式建立和服务的连接,并且得到服务的实例,然后才能调用。下面的例子演示了在Activity调用本地服务,在Activity界面上输入人名,点击确定在按钮的下面显示调用服务的结果:人名":Hello World",步骤如下:

1.创建服务接口,

服务接口提供了服务能提供的供调用者调用的方法。

IService.java

package com.local.service;

public interface IService {
	public String getHelloResult(String name);
}

 

2.服务的实现者

HelloService.java

package com.local.service;

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


public class HelloService extends Service {
    private MyServiceBinder myServiceBinder = new MyServiceBinder();
    @Override
    public IBinder onBind(Intent intent) {
        return myServiceBinder;
    }
    public class MyServiceBinder extends Binder implements IService {
		@Override
		public String getHelloResult(String name) {
			// TODO Auto-generated method stub
			return name+":Hello World";
		}
    }
    
}

 

3.调用服务的Activity

LocalServiceCallDemo.java

package com.local.service;

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.IBinder;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LocalServiceCallDemo extends Activity {

	private EditText mEditText;
	private IService serviceInstance;
	private TextView textView;
	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i("INFO", "Service bound");
			serviceInstance = (IService) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.i("INFO", "Service Unbound");
		}

	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button mButton = (Button) findViewById(R.id.myButton);
		mEditText = (EditText) findViewById(R.id.myEditText);
		textView = (TextView) findViewById(R.id.myTextView01);
		bindService(new Intent("com.local.service.MY_SERVICE"), conn,
				Context.BIND_AUTO_CREATE);
		mButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Editable str;
				str = mEditText.getText();
				String result = serviceInstance.getHelloResult(str.toString());
				textView.setText(result);
			}
		});
	}
}