tak*_*are 3 service android bind aidl
我有问题bindService()。我正在尝试在构造函数中进行绑定,提供一个包含两个可解析附加项的 Intent。构造函数被调用,onResume()服务在它的onBind()方法中解析两个额外的,并且可能null作为解析的结果返回。
当我第一次运行应用程序(通过在 Eclipse 中运行)时,绑定(预期)被服务拒绝:服务的onBind()方法被调用并返回null. 但是,该bindService()方法在应用程序端返回true(它不应该返回,因为绑定没有通过!)。
当我尝试以下操作时,这会变得更成问题:我按下 HOME 按钮并再次启动应用程序(因此它onResume()再次运行并且应用程序尝试再次绑定到服务)。这次服务onBind()似乎甚至没有运行!但应用程序bindService()仍然返回true!
下面是一些示例代码,可以帮助您理解我的问题。
应用端:
// activity's onResume()
@Override
public void onResume() {
super.onResume();
var = new Constructor(this);
}
// the constructor
public Constructor(Context context) {
final Intent bindIntent = new Intent("test");
bindIntent.putExtra("extra1",extra_A);
bindIntent.putExtra("extra2",extra_B);
isBound = context.bindService(bindIntent, connection, Context.BIND_ADJUST_WITH_ACTIVITY);
log("tried to bind... isBound="+isBound);
}
Run Code Online (Sandbox Code Playgroud)
服务端:
private MyAIDLService service = null;
@Override
public void onCreate() {
service = new MyAIDLService(getContentResolver());
}
@Override
public IBinder onBind(final Intent intent) {
log("onBind() called");
if (intent.getAction().equals("test") {
ExtraObj extra_A = intent.getParcelableExtra("extra1");
ExtraObj extra_B = intent.getParcelableExtra("extra2");
if (parse(extra_A,extra_B))
return service;
else {
log("rejected binding");
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在ServiceConnection我使用存在以下onServiceConnected()方法:
@Override
public void onServiceConnected(final ComponentName name, final IBinder service) {
log("onServiceConnected(): successfully connected to the service!");
this.service = MyAIDLService.asInterface(service);
}
Run Code Online (Sandbox Code Playgroud)
所以,我从来没有看到“成功连接到服务!” 日志。我第一次运行应用程序(通过 Eclipse)时,我得到了“拒绝绑定”日志以及“isBound=true”,但从那以后我只得到“isBound=true”,“拒绝绑定”没有再也不会出现了。
我怀疑这可能与 Android 认识到即使我强制拒绝也有成功绑定的可能性有关。理想情况下,我也可以强制“解除绑定”,但这是不可能的:我怀疑这是因为,当我杀死应用程序时,我得到了一个位于onUnbind()服务方法中的日志(即使应该有首先没有约束力!)。
有同样的问题,但意识到我的服务实际上并未启动。也许尝试将“Context.BIND_AUTO_CREATE”添加到标志中,这将导致服务被创建和启动。我不相信 Context.BIND_ADJUST_WITH_ACTIVITY 会启动它,因此可能不会调用 onServiceConnected (即使 bindService() 调用返回 true 也不适合我):
isBound = context.bindService(bindIntent, connection,
Context.BIND_ADJUST_WITH_ACTIVITY | Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6059 次 |
| 最近记录: |