2019-01-15 15:02:50 459浏览
今天扣丁学堂Android培训老师给大家介绍一下关于Android获取其他应用中的assets资源详解,首先有这样一个需求:A应用在一定条件下出发某个逻辑后,需要从B应用中获取一些资源(assets下的mp4视频、还有drawable下的一些图片用作背景),具体需求就不说啦哈哈,用一张图来表示应该更明白:
@Override
public Context createPackageContext(String packageName, int flags)
throws PackageManager.NameNotFoundException {
return mBase.createPackageContext(packageName, flags);
}
public static final int CONTEXT_INCLUDE_CODE = 0x00000001; public static final int CONTEXT_IGNORE_SECURITY = 0x00000002;
//栗子:获取一个drawable 的id
int identifier = bContext.getResources().getIdentifier("bg", "drawable", bContext.getPackageName());
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("GFZY", "onCreate: ");
try {
Context bContext = this.createPackageContext("pers.jibai.matrixtext"
, Context.CONTEXT_INCLUDE_CODE
| Context.CONTEXT_IGNORE_SECURITY);
ClassLoader loader = bContext.getClassLoader();
Class<?> clazz = loader.loadClass("pers.jibai.matrixtext.A");
Object a = clazz.getConstructor().newInstance();
Method getAssetBg = clazz.getMethod("getBgMp4", Context.class);
Log.e("GFZY", "onCreate: " + getAssetBg.getName());
InputStream invoke = (InputStream) getAssetBg.invoke(a, bContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(invoke));
String s = reader.readLine();
reader.close();
((TextView) findViewById(R.id.t)).setText(s);
} catch (Exception e) {
e.printStackTrace();
Log.e("GFZY", "onCreate: " + e.getMessage());
}
}
public class A {
public void asd() {
Log.e("GFZY", "asd:我是matrix ");
}
public InputStream getBgMp4(Context context) {
try {
return context.getAssets().open("asd");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
【关注微信公众号获取更多学习资料】