gpt4 book ai didi

android - Broadcastreceiver组件不允许绑定(bind)到android中的服务

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:46 25 4
gpt4 key购买 nike

这是我正在做的:

public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

ConnectivityManager conn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conn.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();

if (isConnected == true) {

// initChatHub();
Intent serviceIntent = new Intent(context, ChatService.class);
Toast.makeText(context, "Connected", 1000).show();
serviceIntent.putExtras(intent);
context.startService(serviceIntent);
context.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);

} else {
Toast.makeText(context, "Disconnected", 1000).show();
}
}

当网络状态发生变化时应用程序崩溃当我关闭数据连接时没有错误出现当数据连接打开然后应用程序崩溃并且出现此异常请建议我如何修复它。

enter image description here

最佳答案

请参阅此处 Context.bindService :

Note: this method can not be called from a BroadcastReceiver component....

所以,使用 BroadcastReceiver.peekService从运行的服务中返回 IBinder:

 Intent serviceIntent = new Intent(context, ChatService.class);
context.startService(serviceIntent);
if (isConnected == true) {
IBinder binder = peekService(context, new Intent(context, ChatService.class));
Toast.makeText(context, "Connected", 1000).show();
if (binder != null){
mChatService = ((LocalBinder) binder).getService();
//.... other code here
}
}

关于android - Broadcastreceiver组件不允许绑定(bind)到android中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com