请问android app如何启动DexClassLoader动态加载的jar包中定义的service

架构需求就是这样,Service类定义在一个Jar包插件,通过网络下载或者push到SD卡中,然后要求Service在新进程中启动。
运行时出现找不到Service类的错误,然后程序错误崩溃:
Causedby:java.lang.ClassNotFoundException:Didn'tfindclassJarService
贴个简单代码示例吧
主Activity就是loadSD卡上的jar包,反射获取类名,intent启动service
publicclassMainActivityextendsActionBarActivity{
privatefinalStringTAG="MainActivity";
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"onCreate");
ClassLoaderdexLoader=newDexClassLoader("/sdcard/jarservicetest.jar",getCacheDir().getAbsolutePath(),null,getClassLoader());
//ClassLoaderdexLoader=getClassLoader();
try{
Log.i(TAG,"try");
ClassactivityClass=dexLoader.loadClass("com.example.jarservicetest.JarService");
Intentintent=newIntent(this,activityClass);
startService(intent);
}catch(ClassNotFoundExceptione){
Log.i(TAG,"catch");
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
Service就一空壳
publicclassJarServiceextendsService{
privatefinalStringTAG="JARSERVICE";
@Override
publicvoidonCreate(){
//TODOAuto-generatedmethodstub
Log.i(TAG,"onCreate");
super.onCreate();
}
@Override
publicvoidonDestroy(){
//TODOAuto-generatedmethodstub
super.onDestroy();
}
@Override
publicIBinderonBind(Intentarg0){
//TODOAuto-generatedmethodstub
returnnull;
}
}
Manifest文件中声明了Service
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
android:name=".MainActivity"
android:label="@string/app_name">
请教达人们,面对这种需求,有啥解决办法?
慕容森
浏览 360回答 2
2回答

繁花如伊

检查下jarservicetest.jar文件里包含的是class文件还是dex文件拿sdcard路径的时候,用Environment.getExternalStorageDirectory()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript