以前也用过Service,也使用过Service通信的一些方式,比如广播,接口回调之类的,但是不够全面。
最近看到公司项目有跨进程的Service,就系统的学习了一下Service的方方面面,在此总结。
关于Service的基础知识就不在这里描述了,这篇文章只说Service的通信,Service的通信分为两种
A:同进程下的通信
B:跨进程下的通信
下面分别描述:
A:同进程下的通信。
这种情况下Service要和其他组件进行通信,一般是Activity,有如下常见的3种方法
1:使用广播
2:使用Binder
3:使用Binder+接口回调,使用接口回调是为了在service进度变化时主动触发回调
1-------使用广播,在Acticiy中注册广播以及编写广播类,在Service中发送广播
public class MainActivity extends Activity {
private ProgressBar mProgressBar;
private Intent mIntent;
private MsgReceiver msgReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//动态注册广播接收器
msgReceiver = new MsgReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.communication.RECEIVER");
registerReceiver(msgReceiver, intentFilter);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//启动服务
mIntent = new Intent("com.example.communication.MSG_ACTION");
startService(mIntent);
}
});
}
@Override
protected void onDestroy() {
//停止服务
stopService(mIntent);
//注销广播
unregisterReceiver(msgReceiver);
super.onDestroy();
}
/**
* 广播接收器
*
*
*/
public class MsgReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//拿到进度,更新UI
int progress = intent.getIntExtra("progress", 0);
mProgressBar.setProgress(progress);
}
}
}
<pre name="code" class="java">public class MsgService extends Service {
/**
* 进度条的最大值
*/
public static final int MAX_PROGRESS = 100;
/**
* 进度条的进度值
*/
private int progress = 0;
private Intent intent = new Intent("com.example.communication.RECEIVER");
/**
* 模拟下载任务,每秒钟更新一次
*/
public void startDownLoad(){
new Thread(new Runnable() {
@Override
public void run() {
while(progress < MAX_PROGRESS){
progress += 5;
//发送Action为com.example.communication.RECEIVER的广播
intent.putExtra("progress", progress);
sendBroadcast(intent);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startDownLoad();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
2-------使用Binder
public class LocalService extends Service { // Binder given to clients private final IBinder mBinder = new LocalBinder(); // Random number generator private final Random mGenerator = new Random(); /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } /** method for clients */ public int getRandomNumber() { return mGenerator.nextInt(100); } }
LocalBinder
为客户端提供 getService()
方法,以获取LocalService
的当前实例。这样,客户端便可调用服务中的公共方法。 例如,客户端可调用服务中的 getRandomNumber()
。
点击按钮时,以下这个 Activity 会绑定到 LocalService
并调用 getRandomNumber()
:
public class BindingActivity extends Activity { LocalService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocalService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } /** Called when a button is clicked (the button in the layout file attaches to * this method with the android:onClick attribute) */ public void onButtonClick(View v) { if (mBound) { // Call a method from the LocalService. // However, if this call were something that might hang, then this request should // occur in a separate thread to avoid slowing down the activity performance. int num = mService.getRandomNumber(); Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); } } /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; }取自谷歌官方doc的demo。
public interface OnProgressListener {
void onProgress(int progress);
}
public class MsgService extends Service {
/**
* 进度条的最大值
*/
public static final int MAX_PROGRESS = 100;
/**
* 进度条的进度值
*/
private int progress = 0;
/**
* 更新进度的回调接口
*/
private OnProgressListener onProgressListener;
/**
* 注册回调接口的方法,供外部调用
* @param onProgressListener
*/
public void setOnProgressListener(OnProgressListener onProgressListener) {
this.onProgressListener = onProgressListener;
}
/**
* 增加get()方法,供Activity调用
* @return 下载进度
*/
public int getProgress() {
return progress;
}
/**
* 模拟下载任务,每秒钟更新一次
*/
public void startDownLoad(){
new Thread(new Runnable() {
@Override
public void run() {
while(progress < MAX_PROGRESS){
progress += 5;
//进度发生变化通知调用方
if(onProgressListener != null){
onProgressListener.onProgress(progress);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* 返回一个Binder对象
*/
@Override
public IBinder onBind(Intent intent) {
return new MsgBinder();
}
public class MsgBinder extends Binder{
/**
* 获取当前Service的实例
* @return
*/
public MsgService getService(){
return MsgService.this;
}
}
}
public class MainActivity extends Activity {
private MsgService msgService;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//绑定Service
Intent intent = new Intent("com.example.communication.MSG_ACTION");
bindService(intent, conn, Context.BIND_AUTO_CREATE);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//开始下载
msgService.startDownLoad();
}
});
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//返回一个MsgService对象
msgService = ((MsgService.MsgBinder)service).getService();
//注册回调接口来接收下载进度的变化
msgService.setOnProgressListener(new OnProgressListener() {
@Override
public void onProgress(int progress) {
mProgressBar.setProgress(progress);
}
});
}
};
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
}
B:跨进程通信
a----Messenger
使用 Messenger
如需让服务与远程进程通信,则可使用 Messenger
为您的服务提供接口。利用此方法,您无需使用 AIDL 便可执行进程间通信 (IPC)。
以下是 Messenger
的使用方法摘要:
- 服务实现一个
Handler
,由其接收来自客户端的每个调用的回调 Handler
用于创建Messenger
对象(对Handler
的引用)Messenger
创建一个IBinder
,服务通过onBind()
使其返回客户端- 客户端使用
IBinder
将Messenger
(引用服务的Handler
)实例化,然后使用后者将Message
对象发送给服务 - 服务在其
Handler
中(具体地讲,是在handleMessage()
方法中)接收每个Message
这样,客户端并没有调用服务的“方法”。而客户端传递的“消息”(Message
对象)是服务在其 Handler
中接收的。
以下是一个使用 Messenger
接口的简单服务示例:
public class MessengerService extends Service { /** Command to the service to display a message */ static final int MSG_SAY_HELLO = 1; /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SAY_HELLO: Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show(); break; default: super.handleMessage(msg); } } } /** * Target we publish for clients to send messages to IncomingHandler. */ final Messenger mMessenger = new Messenger(new IncomingHandler()); /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ @Override public IBinder onBind(Intent intent) { Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show(); return mMessenger.getBinder(); } }
请注意,服务就是在 Handler
的 handleMessage()
方法中接收传入的 Message
,并根据 what
成员决定下一步操作。
客户端只需根据服务返回的 IBinder
创建一个 Messenger
,然后利用 send()
发送一条消息。例如,以下就是一个绑定到服务并向服务传递 MSG_SAY_HELLO
消息的简单 Activity:
public class ActivityMessenger extends Activity { /** Messenger for communicating with the service. */ Messenger mService = null; /** Flag indicating whether we have called bind on the service. */ boolean mBound; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the object we can use to // interact with the service. We are communicating with the // service using a Messenger, so here we get a client-side // representation of that from the raw IBinder object. mService = new Messenger(service); mBound = true; } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. mService = null; mBound = false; } }; public void sayHello(View v) { if (!mBound) return; // Create and send a message to the service, using a supported 'what' value Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0); try { mService.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); // Bind to the service bindService(new Intent(this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } }
请注意,此示例并未说明服务如何对客户端作出响应。如果您想让服务作出响应,则还需要在客户端中创建一个 Messenger
。然后,当客户端收到onServiceConnected()
回调时,会向服务发送一条 Message
,并在其 send()
方法的 replyTo
参数中包含客户端的 Messenger
。
使用方法(AndroidStudio)
我发现现在AIDL的教程基本上还是eclipse的,但是在AndroidStudio里面使用AIDL还是有一些不同的,来看看怎么用,首先新建一个工程当做server服务端:
创建好后在任意文件夹右键New-->AIDL-->AIDL File,编辑文件名后会自动在src/main目录下面新建aidl文件夹,包的目录结构如下:
- main
- aidl
- com.example.tee.testapplication.aidl
- java
- com.example.tee.testapplication
- res
- AndroidManifest.xml
- aidl
自动生成的aidl文件如下:
// AidlInterface.aidl
package com.example.tee.testapplication.aidl;
// Declare any non-default types here with import statements
interface AidlInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
我们可以看到aidl文件的代码格式跟java很像,支持java的基础类型以及List、Map等,如果是自定义类的话需要手动导入,我们后面再说,先来最简单的,新建一个 IMyAidlInterface.aidl文件,修改如下:
package com.example.tee.testapplication.aidl;
interface IMyAidlInterface {
String getValue();
}
在接口中定义一个getValue方法,返回一个字符串,现在可以编译一下工程,找到app/build/generated/source/aidl/debug目录,在我们应用包名下会发现生成了一个Interface类,名字跟我们定义的aidl的文件名字一样,这说明其实aidl文件在最后还是会转换成接口来实现,而且这个文件不需要我们维护,在编译后自动生成。
然后新建一个类继承Service:
public class MAIDLService extends Service{
public class MAIDLServiceImpl extends IMyAidlInterface.Stub{
@Override
public String getValue() throws RemoteException {
return "get value";
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new MAIDLServiceImpl();
}
}
在MAIDLService类中定义一个内部类继承IMyAidlInterface.Stub,并且重写我们在aidl也就是在接口中定义的getValue方法,返回字符串get value。
到了这里,我们就新建好了这个服务端,作用是在调用后返回一个字符串,最后在AndroidManifest文件中声明:
<service
android:name=".MAIDLService"
android:process=":remote"//加上这句的话客户端调用会创建一个新的进程
android:exported="true"//默认就为true,可去掉,声明是否可以远程调用
>
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="com.example.tee.testapplication.aidl.IMyAidlInterface" />
</intent-filter>
</service>
android:process=":remote"这一行的作用是声明是否调用时新建进程,接下来写客户端代码,新建一个工程,将刚才创建的aidl文件拷贝到这个工程中,注意同样也是要放在aidl文件夹下,然后在MainActivity中编写代码如下:
public class MainActivity extends AppCompatActivity {
private TextView mValueTV;
private IMyAidlInterface mAidlInterface = null;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAidlInterface = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent("com.example.tee.testapplication.aidl.IMyAidlInterface");
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
mValueTV = (TextView) findViewById(R.id.tv_test_value);
mValueTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mValueTV.setText(mAidlInterface.getValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onDestroy() {
if(mAidlInterface != null){
unbindService(mServiceConnection);
}
super.onDestroy();
}
}
注意这里新建Intent的传入的参数字符串是在manifest里面自定义的action标签,并且在onDestroy记得取消绑定服务。
执行结果就是我们在点击TextView时会显示服务端给我们返回的get value字符串
自定义的对象
刚才我们使用的是基础类型String,在使用我们自己定义的类的时候用上面的方法是不行的,用我们自定义的类需要手动导入,修改刚才我们创建的作为服务端的工程
首先在开始生成的aidl包下(所有aidl相关的文件都要放在这个包下)新建Student.java
public class Student implements Parcelable{
public String name;
public int age;
protected Student(Parcel in) {
readFromParcel(in);
}
public Student() {
}
public static final Creator<Student> CREATOR = new Creator<Student>() {
@Override
public Student createFromParcel(Parcel in) {
return new Student(in);
}
@Override
public Student[] newArray(int size) {
return new Student[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(age);
dest.writeString(name);
}
public void readFromParcel(Parcel in){
age = in.readInt();
name = in.readString();
}
@Override
public String toString() {
return String.format(Locale.ENGLISH, "STUDENT[%s:%d]", name, age);
}
}
需要实现Parcelable序列化接口,AndroidStudio会自动生成静态内部类CREATOR和describeContents方法,这些部分我们都不需要修改,用自动生成的就好。然后重写writeToParcel方法,自定义readFromParcel方法,注意这两个方法里面的属性顺序必须一致,一个是写入,一个是读取。在构造方法Student(Parcel in)中调用readFromParcel(in)方法。
接下来新建Student.aidl文件(也是在aidl包中):
// Student.aidl
package com.example.tee.testapplication.aidl;
// Declare any non-default types here with import statements
parcelable Student;
注意这里Student前面的关键字parcelable首字母是小写哦,再修改IMyAidlInterface.aidl文件如下:
// IMyAidlInterface.aidl
package com.example.tee.testapplication.aidl;
// Declare any non-default types here with import statements
import com.example.tee.testapplication.aidl.Student;
interface IMyAidlInterface {
Student getStudent();
void setStudent(in Student student);
String getValue();
}
定义了两个方法,一个是设置Student,一个是获取Student,在setStudent这个方法注意参数在类型前面有个in关键字,在aidl里参数分为in输入,out输出
现在在MAIDLService.java中重写新加的两个方法:
private Student mStudent;
public class MAIDLServiceImpl extends IMyAidlInterface.Stub{
@Override
public Student getStudent() throws RemoteException {
return mStudent;
}
@Override
public void setStudent(Student student) throws RemoteException {
mStudent = student;
}
@Override
public String getValue() throws RemoteException {
return "get value : " + Thread.currentThread().getName() + Thread.currentThread().getId();
}
}
服务端代码修改完毕,来到客户端工程,同样要把刚才的aidl包下的文件拷贝覆盖过来,保持两边一致,然后在MainActivity.java中修改如下:
mValueTV = (TextView) findViewById(R.id.tv_test_value);
mStudentTV = (TextView) findViewById(R.id.tv_test_student);
mValueTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mValueTV.setText(mAidlInterface.getValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
mStudentTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Student student = new Student();
student.age = 10;
student.name = "Tom";
mAidlInterface.setStudent(student);
mStudentTV.setText(mAidlInterface.getStudent().toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
现在编译工程,会发现工程会报错,找不到类Student,我们需要在app目录下的build.gradle文件添加代码如下:
android {
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java', 'src/main/aidl']
resources.srcDirs = ['src/main/java', 'src/main/aidl']
aidl.srcDirs = ['src/main/aidl']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['src/main/assets']
}
}
}
也就是指定一下文件目录,现在再编译就没有问题了
总结
Android的IPC使用起来还是挺简单的,AIDL文件的语法也跟我们平时使用接口的时候很相似,但是它只支持基础类型,只能引用AIDL文件,需要使用自定义类的时候要稍微麻烦一点。