Mat*_*ska 33 service binding android speech-recognition
我有一个特殊情况:由广播接收器启动的服务启动一项活动.我希望此活动能够与服务进行通信.我选择使用AIDL来实现它.除了活动中的bindService()方法之外,一切似乎都很好onCreate().实际上,bindService()抛出一个空指针异常,因为在服务方法时onServiceConnected()从不调用onBind().无论如何bindService()返回true.该服务显然是活跃的,因为它启动了活动.我知道从服务中调用活动可能听起来很奇怪,但不幸的是,这是在服务中进行语音识别的唯一方法.
提前致谢
Kom*_*ave 45
我刚刚遇到了这个问题的另一个版本,同样的症状是onServiceConnected(...)没有被调用.在我的情况下,原因是不同的.
您必须确保在应用程序标记内的AndroidManifest.xml中有一个服务声明 - 这是我的问题的根源.
<application android:name=".YourAppTitle" android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main" android:label="@string/app_name">
</activity>
<service android:name="YourService" />
</application>
Run Code Online (Sandbox Code Playgroud)
如果你在Eclipse中使用一个单独的Android库,会有一个额外的复杂性 - 如果引用的服务与清单位于同一个包中,那么添加此Service标记似乎只能解决问题.即如果您的应用程序在包abc中并且这是AndroidManifest.xml所在的位置,那么'YourService'也必须在包abc中(如果需要,可以从另一个库中手动复制),否则<service..>标签可能/将被忽略并onServiceConnected(...)仍然赢得'被称为.
即使我在代码中为服务使用了合适的import语句,我的项目就是这种情况.Eclipse没有显示任何错误,因此导入正确地从Eclipse工作区中的另一个库中识别该类.
HTH
小智 44
经过几个小时的尝试来解决这个问题,问题是显示服务创建的示例不包含onBind方法,或者它们具有以下示例代码或者它为您生成:
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
Run Code Online (Sandbox Code Playgroud)
这会导致onServiceConnected方法失败或从未实际执行.修复非常简单,具体如下:
public IBinder onBind(Intent intent) {
return mBinder;
}
Run Code Online (Sandbox Code Playgroud)
您可以在哪里创建一个简单的绑定器,如下所示:
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public ConferenceService getService() {
return ConferenceService.this;
}
}
Run Code Online (Sandbox Code Playgroud)
Ian*_*GSY 26
该onServiceConnected事件从未被称为在我的应用程序.
问题是我在我的Application Manifest中定义了服务名称:
<service android:name="MyService" android:enabled="true"></service>
Run Code Online (Sandbox Code Playgroud)
一旦我将其更改为完整的类名,它就可以工作:
<service android:name="com.example.MyService" android:enabled="true"></service>
Run Code Online (Sandbox Code Playgroud)
更新:您还可以使用相对类名:
<service android:name=".MyService" android:enabled="true"></service>
Run Code Online (Sandbox Code Playgroud)
使用完整的com.example.MyServiceClass而不仅仅是MyServiceClass指定类名.
MrS*_*ake 13
我无法用你的描述来弥补确切的问题,所以我猜这里!
怎么可以bindService()抛出NullPointerException?这可能(/应)发生的唯一方法是,当你不提供Service或ServiceConnection监听.
bindService()不能扔一个NullPointerException 因为 onServiceConnected()没有叫.呼叫onServiceConnected()是一种产品bindService().
所以我猜你AIDL在Service实际粘合之前调用了一种方法?
小智 8
还有一件事是,如果你在bindservice方法中调用方法,oncreate那么onserviceconnected在oncreate方法完成后调用.
因此,在oncreate结束之前(或之前onserviceconnected调用之前)对接口函数的任何引用都会显示空指针异常.
原始问题的另一个原因可能是该服务尚未运行,并且您将0作为标志传递给bindService。像这样:
bindService(intent, serviceConnection, 0);
Run Code Online (Sandbox Code Playgroud)
您要寻找的是:
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41374 次 |
| 最近记录: |