Android使用bindService作为中间人对象开启服务

项目结构如下:

Android使用bindService作为中间人对象开启服务-LMLPHP

MyService:

package com.demo.secondservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast; public class MyService extends Service {
public MyService() {
} @Override
public IBinder onBind(Intent intent) { return new MyBind();
} public void banZheng(int money) { if(money>1000){
Toast.makeText(getApplicationContext(), "帮你办", Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(), "钱少,不办", Toast.LENGTH_LONG).show(); }
} //定义中间人
public class MyBind extends Binder{ public void callBanZheng(int money){ //调用办证的方法
banZheng(money); } }
}

MainActivity:

package com.demo.secondservice;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; public class MainActivity extends AppCompatActivity {
MyConn myConn;
MyService.MyBind myBind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, MyService.class);
// startService(intent);
//连接服务
myConn = new MyConn();
bindService(intent,myConn,BIND_AUTO_CREATE);
} public void click(View view) { //自己new对象 脱离了谷歌框架
// MyService myService = new MyService();
myBind.callBanZheng(10200); } //监视服务的状态
private class MyConn implements ServiceConnection{ //当服务连接成功调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) { myBind = (MyService.MyBind) service; } //失去连接
@Override
public void onServiceDisconnected(ComponentName name) { }
} @Override
protected void onDestroy() { //解绑服务
unbindService(myConn);
super.onDestroy();
}
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" /> <Button
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开启服务"
/> </android.support.constraint.ConstraintLayout>
05-11 13:08