如果服务在另一个进程中,该如何绑定? [英] How to bind Service if it's in another process?
问题描述
清单:
<service android:name="com.example.MainService" android:process=":main_service"/>
尝试在活动"中绑定服务:
Trying to bind service in Activity:
public class MainActivity extends Activity {
MainService mMainService;
private boolean mBound;
@Override
protected void onCreate(Bundle savedInstanceState) {
bindService(intentForMainService, mConnection, Context.BIND_AUTO_CREATE)
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MainService.MainServiceBinder binder = (MainService.MainServiceBinder) service;//HERE IS EXCEPTION
mMainService = (MainService) binder.getService();
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
mMainService = null;
mBound = false;
}
};
@Override
protected void onStop() {
doUnbindService();
super.onStop();
}
void doUnbindService() {
if (mBound) {
unbindService(mConnection);
}
}
}
错误:
FATAL EXCEPTION: main
Process: com.hos.android, PID: 9001
java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.example.service.main.MainService$MainServiceBinder
at com.example.ui.base.BaseServiceActivity$1.onServiceConnected(MainActivity.java:34)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1335)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1352)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
但是当我删除此 android:process =:main_service" 时,一切都正常
But when I delete this android:process=":main_service" all works properly
推荐答案
步骤1:编写一个AIDL文件,该文件描述了客户端可以绑定到的服务要导出的接口.出于此答案的目的,我将此接口称为Foo
,因此AIDL文件将为Foo.aidl
.请注意,如果客户端和服务位于单独的Android Studio模块中,并且两者都需要相同的Foo.aidl
内容.
Step #1: Write an AIDL file that describes the interface to be exported by the service that clients can bind to. For the purposes of this answer, I will call this interface Foo
, and so the AIDL file would be Foo.aidl
. Note that if the client and service are in separate Android Studio modules that both need the same Foo.aidl
content.
步骤2:让服务的资料夹扩展Foo.Stub
并覆盖Foo.Stub
上的方法,而不是扩展IBinder
.
Step #2: Have your service's binder extend Foo.Stub
and override the methods on Foo.Stub
, instead of extending IBinder
.
步骤3:在客户端的onServiceConnected()
中,通过Foo.Stub.asInterface(service)
将原始活页夹转换为Foo
实例,并且Foo
具有AIDL定义的API的客户端.
Step #3: In your client, in onServiceConnected()
, convert the raw binder to a Foo
instance via Foo.Stub.asInterface(service)
, and Foo
has the client side of the AIDL-defined API.
这对示例项目对此进行了说明,其中我的情况是,客户端和服务位于单独的应用程序中.
This pair of sample projects illustrates this, where in my case the client and the service are in separate apps.
这篇关于如果服务在另一个进程中,该如何绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!