• 首页
  • 云服务器
  • 虚拟主机
  • 物理服务器
  • 大带宽
  • 跨境电商
  • 保障
    信任中心 >>
    • 基础设施与网络
    • 服务保障能力
    • 数据安全
    • 合规资质
    数据中心 >>
    • 中国洛阳国际数据中心
    • 中国香港多线数据中心
    VIP会员服务 >>
    • 7*24小时服务支持
    • 0元快速备案
    • 100倍故障赔偿
    • 5天无理由退款
会员登录 免费注册

帮助中心 / Android 中怎么动态加载 jar 文件

Android 中怎么动态加载 jar 文件



来源:辰迅云编辑:chenxun时间:2021/6/28 22:33:00



Android 中怎么动态加载 jar 文件,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

1.1  首先需要了解一点:在Android中可以动态加载,但无法像Java中那样方便动态加载jar

      原因:Android的虚拟机(Dalvik VM)是不认识Java打出jar的byte code,需要通过dx工具来优化转换成Dalvik byte code才行。这一点在咱们Android项目打包的apk中可以看出:引入其他Jar的内容都被打包进了classes.dex。

      所以这条路不通,请大家注意。

1.2  当前哪些API可用于动态加载

   1.2.1  DexClassLoader

      这个可以加载jar/apk/dex,也可以从SD卡中加载,也是本文的重点。

   1.2.2  PathClassLoader  

      只能加载已经安装到Android系统中的apk文件。

1.3  代码

     package com.example.dynamicloaddemo.jar;
    
   public class DynamicTest implements IDynamic {
    
       @Override       public String helloWorld() {
        return "Hello World Form JAR";
       }
    
   }

   将这个类导出,注意,编译的时候必须是 java 1.6 编译(java 1.7 编译会出现错误:Zip is good, but no classes.dex inside, and no valid .odex file in the same directory)

1.4  编译文件之后将上面的类打包为 dynamic.jar 

        1.4.1  下载jar 转化 dex 工具,将打包好的jar拷贝到SDK安装目录android-sdk-windows\platform-tools下,DOS进入这个目录,执行命名: dx --dex --output=test.jar dynamic.jar

        1.4.2  将test.jar拷贝到 /data/data/packagename/app-libs/ 

放在 SDCard 上会出现错误   Optimized data directory /data/data/com.example.dynamicloaddemo/files/test.jar is not owned by the current user.  Shared storage cannot protect your application from code injection attacks.

image.png

程序代码:

public class MainActivity extends Activity {
Button mToastButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToastButton = (Button) findViewById(R.id.main_btn);// Before the secondary dex file can be processed by the DexClassLoader,// it has to be first copied from asset resource to a storage location.// final File dexInternalStoragePath = new File(getDir("dex",// Context.MODE_PRIVATE),SECONDARY_DEX_NAME);// if (!dexInternalStoragePath.exists()) {// mProgressDialog = ProgressDialog.show(this,// getResources().getString(R.string.diag_title),// getResources().getString(R.string.diag_message), true, false);// // Perform the file copying in an AsyncTask.// // 从网络下载需要的dex文件// (new PrepareDexTask()).execute(dexInternalStoragePath);// } else {// mToastButton.setEnabled(true);// }System.out.println(getDir("libs", Context.MODE_PRIVATE));
System.out.println(getFilesDir());
System.out.println(getCacheDir());
System.out.println(getDir("libs", Context.MODE_PRIVATE));
System.out.println(getDir("libs", Context.MODE_PRIVATE));
mToastButton.setOnClickListener(new View.OnClickListener() {public void onClick(View view) {// Internal storage where the DexClassLoader writes the// optimized dex file to.// final File optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);final File optimizedDexOutputPath = new File(getDir("libs", Context.MODE_PRIVATE) + File.separator + "test.jar");// Initialize the class loader with the secondary dex file.// DexClassLoader cl = new// DexClassLoader(dexInternalStoragePath.getAbsolutePath(),// optimizedDexOutputPath.getAbsolutePath(),// null,// getClassLoader());/*
DexClassLoader cl = new DexClassLoader(optimizedDexOutputPath.getAbsolutePath(), Environment
.getExternalStorageDirectory().toString(), null, getClassLoader());
*/DexClassLoader cl = new DexClassLoader(optimizedDexOutputPath.getAbsolutePath(), getDir("libs", Context.MODE_PRIVATE).getAbsolutePath(), null, getClassLoader());
Class<?> libProviderClazz = null;try {// Load the library class from the class loader.// 载入从网络上下载的类// libProviderClazz =// cl.loadClass("com.example.dex.lib.LibraryProvider");libProviderClazz = cl.loadClass("com.example.dynamicloaddemo.jar.DynamicTest");// Cast the return object to the library interface so that// the// caller can directly invoke methods in the interface.// Alternatively, the caller can invoke methods through// reflection,// which is more verbose and slow.// LibraryInterface lib = (LibraryInterface)// libProviderClazz.newInstance();IDynamic lib = (IDynamic) libProviderClazz.newInstance();// Display the toast!// lib.showAwesomeToast(view.getContext(), "hello 世界!");Toast.makeText(MainActivity.this, lib.helloWorld(), Toast.LENGTH_SHORT).show();
} catch (Exception exception) {// Handle exception gracefully here.exception.printStackTrace();
}
}
});
}
}

1.5  运行,出现 Hello World From JAR , 表明动态加载成功。

 

看完上述内容,你们掌握Android 中怎么动态加载 jar 文件的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注辰讯云资讯频道,感谢各位的阅读!






上一篇:android 中怎么提高App的启动速度
下一篇:Android中怎么使用ViewPager实现左右循环滑动效果
相关阅读
  • ●怎么选择海外vps?如何判断哪个海外vps更好?
  • ●YII2框架中如何通过Composer安装扩展插
  • ●游戏高防服务器租用哪个好?
  • ●Linux中有哪些常见的问题
  • ●layui中如何设置checkbox勾选
  • ●js怎么实现图片3D轮播效果
  • ●香港服务器并发量怎么计算?
  • ●JournalNode有什么用
  • ●高防ip和高防cdn的防御有什么不同?
  • ●CSS布局中BFC的详细介绍

    帮助中心

  • 云服务器类
  • 域名类
  • 虚拟主机类
  • 独立服务器
  • 付款类
  • 其他类
标签云
  • 海外服务器
  • 香港服务器
  • 高防服务器

现在注册,即刻为您提供最佳上云实践机会

立即注册
辰迅云

400-0666-318 (7*24小时热线)

Copyright 2013 - chenxunyun.com. All RightsReserved. 辰迅云 版权所有
  • 关于辰迅云

    关于我们 发展历程 资质荣誉 新闻公告 诚聘英才 联系我们
  • 辰迅云产品

    云服务器 服务器托管 服务器租用 >
  • 服务与支持

    域名知识 云服务器问题 SSL证书问题 虚拟主机问题 租用托管 网站备案问题
  • 快速通道

    独立控制面板 忘记密码
乐创云 ASP300源码 whmcs之家
  • 工信部备案号沪ICP备20007084号
  • 《中华人民共和国增值电信业务经营许可证》编号: B1-20194590号

在线客服

电话咨询

微信客服