Android Service之绑定本地服务

1、定义Service

public class MyService extends Service {

	/**
	 * binder对象会在客户端绑定服务之后,作为参数之一传给
	 * ServiceConnection实现类的onServiceConnected(,)
	 * 方法
	 */
	private final Binder binder = new LocalBinder(); 
	private final Random random = new Random();
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return binder;
	}

	//自定义LocalBinder类,必须包含一个公有的
	//方法,返回MyService类的实例,给客户端
	public class LocalBinder extends Binder {

		public MyService getService() {
			return MyService.this;
		}
	}

	/**
	 * 给客户端调用的方法
	 * @return
	 */
	public int getRandomNum() {
		return random.nextInt(30);
	}
}

在定义服务类Service时需要注意三点:1>继承基类Binder的LocalBinder类中,需要有一个public方法返回当前MyServic的实例,该实例用于客户端访问服务中的方法或属性。2>定义一个由Binder引用的LocalBinder对象,该对象在服务完成绑定之后作为参数传递给ServiceConnection实现类的onServiceConnected(,)方法,在客户端,可以通过该对象获取服务的实例对象。3>在服务中定义客户端可以访问的方法,例如获取随机数的方法getRandmNum()。在Service中,以上三点是串在一起的,保证客户端可以获取到服务实例和调用服务的方法。

2、客户端Activity

@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Intent intent = new Intent(MainActivity.this, MyService.class);
		bindService(intent, conn, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mBind) {
			unbindService(conn);
			mBind = false;
		}
	}

	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mBind = false;
		}

		/**
		 * binder 就是Service中创建的LocalBinder对象
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			// TODO Auto-generated method stub
			mBind = true;
			LocalBinder localBinder = (LocalBinder) binder;// 获取服务中的LocalBinder实例
			myService = localBinder.getService();// 通过实例获得服务MyService的实例
		}
	};
在上面的代码中,按照官方文档,将绑定服务的操作和解绑操作分别放在star()和stop()方法中。最重要的是使用内部类的方式实现ServiceConnection接口,重写onServcieConnected(,)和onServcieDisconnected()方法,这两个方法不再做介绍。

在客户端成功绑定服务时,会回调onServiceConnected(,)方法,其中将服务类创建的LocalBinder对象(其引用类型为Binder)传递给客户端,在客户端对binder对象进行强转化为LocalBinder类型,并通过LocalBinder类的getService()方法得到服务实例对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你编写一个Android本地服务来计算BMI。BMI是通过体重(公斤)除以身高(米)的平方计算得出的,以下是代码示例: 1. 创建一个名为"BMI"的Android服务类,实现以下接口: ``` public class BMI extends Service { @Override public IBinder onBind(Intent intent) { return null; } public float calculateBMI(float height, float weight) { // 计算BMI,返回计算结果 return weight / (height * height); } } ``` 2. 在你的Activity中,绑定并启动服务,并调用calculateBMI方法: ``` public class MainActivity extends AppCompatActivity { private BMI mBMI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 绑定服务 Intent intent = new Intent(this, BMI.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 获取服务实例 BMI.LocalBinder binder = (BMI.LocalBinder) service; mBMI = binder.getService(); } @Override public void onServiceDisconnected(ComponentName name) { mBMI = null; } }; public void calculateBMI(View view) { // 获取用户输入的身高、体重 EditText heightEditText = findViewById(R.id.height_edit_text); EditText weightEditText = findViewById(R.id.weight_edit_text); float height = Float.parseFloat(heightEditText.getText().toString()); float weight = Float.parseFloat(weightEditText.getText().toString()); // 调用服务的方法计算BMI float bmi = mBMI.calculateBMI(height, weight); // 显示结果 TextView resultTextView = findViewById(R.id.result_text_view); resultTextView.setText(String.format("您的BMI指数为:%.2f", bmi)); } @Override protected void onDestroy() { super.onDestroy(); // 解除绑定 unbindService(mConnection); } } ``` 3. 在布局文件中添加EditText、Button和TextView: ``` <EditText android:id="@+id/height_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberDecimal" android:hint="请输入身高(米)"/> <EditText android:id="@+id/weight_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberDecimal" android:hint="请输入体重(公斤)"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="计算BMI" android:onClick="calculateBMI"/> <TextView android:id="@+id/result_text_view" android:layout_width="match_parent" android:layout_height="wrap_content"/> ``` 这样,当用户点击"计算BMI"按钮时,就会调用服务的calculateBMI方法计算BMI,并将结果显示在TextView中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值