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


架构需求就是这样,Service类定义在一个Jar包插件,通过网络下载或者push到SD卡中,然后要求Service在新进程中启动。

运行时出现找不到Service类的错误,然后程序错误崩溃:
Caused by: java.lang.ClassNotFoundException: Didn't find class JarService

贴个简单代码示例吧

主Activity就是load SD卡上的jar包,反射获取类名,intent启动service


 public class MainActivity extends ActionBarActivity {

private final String TAG = "MainActivity";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            Log.i(TAG, "onCreate");

            ClassLoader dexLoader = new DexClassLoader("/sdcard/jarservicetest.jar", getCacheDir().getAbsolutePath(), null, getClassLoader());



            //ClassLoader dexLoader = getClassLoader();



            try {

                    Log.i(TAG, "try");

                    Class<?> activityClass =         dexLoader.loadClass("com.example.jarservicetest.JarService");

                    Intent intent = new Intent(this, activityClass);

                    startService(intent);

            } catch (ClassNotFoundException e) {

                    Log.i(TAG, "catch");

                    // TODO Auto-generated catch block

                    e.printStackTrace();

            }

    }

}

Service就一空壳


 public class JarService  extends Service{

    private final String TAG = "JARSERVICE";

    @Override

    public void onCreate() {

            // TODO Auto-generated method stub

            Log.i(TAG, "onCreate");

            super.onCreate();

    }

    @Override

    public void onDestroy() {

            // TODO Auto-generated method stub

            super.onDestroy();

    }

    @Override

    public IBinder onBind(Intent arg0) {

            // TODO Auto-generated method stub

            return null;

    }

}

Manifest文件中声明了Service
<application


 android:allowBackup="true"

    android:icon="@drawable/ic_launcher"

    android:label="@string/app_name"

    android:theme="@style/AppTheme" >

    <activity

        android:name=".MainActivity"

        android:label="@string/app_name" >

        <intent-filter>

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />


        </intent-filter>

    </activity>

    <service android:name="com.example.jarservicetest.JarService" >

        <!-- android:process=":process1"> -->

    </service>

请教达人们,面对这种需求,有啥解决办法?

Android service java dexclassloader 插件

娜娜莉是我老婆 10 years, 3 months ago
  • 检查下 jarservicetest.jar 文件里包含的是class文件还是dex文件
  • 拿sdcard路径的时候,用 Environment.getExternalStorageDirectory()
超薄浮点草莓味 answered 10 years, 3 months ago

Your Answer