栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

每次我声明并运行两个服务时,都获取java.lang.ClassCastException:android.os.BinderProxy

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

每次我声明并运行两个服务时,都获取java.lang.ClassCastException:android.os.BinderProxy

经过研究和调试后找到了答案,

如果我们创建任何服务并将其绑定到MainApplication类(然后将服务绑定到整个ApplicationContext或baseContext),并且如果同一个应用程序包含绑定到特定于活动的上下文的其他服务,

//Declared in MainApplication@Overridepublic void onServiceConnected(ComponentName className, IBinder service) {     mBinder = (LocalBinder) service;     }

在OnServiceConnected()中,我们将同时获取Services的绑定对象(在 MainApplication中
启动的SecondService(在baseContext中注册)将获取本地bindObject)类和 FirstService
启动的MainActivity(将获取 android.os.binderProxyObject,从而导致ClassCastException )。

  • 因此,要 解决* 此问题,必须从任何活动上下文而不是使用任何全局应用程序上下文启动所有应用程序服务。此外,此问题与 流程 无关 *

  • 因此,我将SecondService和FirstService都移到了MainActivity Context中,从而解决了该问题。

MainActivity.java

    private Button mLanchServiceBtn;    private SecondService.LocalBinder mBinder;    private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) {     mBinder = (LocalBinder) service; } @Override public void onServiceDisconnected(ComponentName arg0) { }     };        @Override        protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLanchServiceBtn=(Button) findViewById(R.id.launch_btn); mLanchServiceBtn.setonClickListener(this); //starting second service in activity Intent launch=new Intent(this,SecondService.class); startService(launch); //Binding to it  bindService(launch, mConnection, BIND_AUTO_CREATE);        }        @Override        public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true;        }        @Override        public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) {     return true; } return super.onOptionsItemSelected(item);        }        @Override        public void onClick(View v) {//Starting FirstService also from MainActivity Intent launch=new Intent(this,FirstService.class); startService(launch);        }    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414036.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号