Edg*_*dge 3 android broadcastreceiver
这是我在做的事情:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当网络状态改变然后应用程序变得崩溃当我的数据连接关闭然后没有错误来到数据连接然后应用程序变得崩溃和这个异常来请建议我如何解决它.

ρяσ*_*я K 12
注意:无法从BroadcastReceiver组件调用此方法....
因此,使用从运行Service 返回的BroadcastReceiver.peekServiceIBinder:
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
}
}
Run Code Online (Sandbox Code Playgroud)
Android返回此异常的原因是Receiver生命周期.它可能很短.如果接收者绑定服务,接收者可能不存在,直到结果返回.看到这里接收器生命周期.
解决方案是启动另一个中间服务.让中间服务绑定目标服务.这个中间服务可以存在,直到结果返回.接收器可以在任何时候被杀死.
还有另一个黑客解决方案可以跳过Android NotAllowException.此异常检查上下文.如果此Context来自Receiver,则Android返回Exception.改变你的代码
context.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)
至
context.getApplicationContext.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)
这种破解解决方案不会保持接收者的生命.如果您认为绑定服务的结果并不重要.您可以使用此hack解决方案跳过NotAllowException.
| 归档时间: |
|
| 查看次数: |
7846 次 |
| 最近记录: |