1、首先在AndroidManifest.xml中的<manifest>中加入android:sharedUserId="共享id"—-具有相同id的apk可以不受限制訪問。
2、根據包名創建Context,在Activity下有提供方法createPackageContext能夠依據包名創建。
3、獲取共享的Apk資源。
註意:
1、Activity中的findViewById()與View中的findViewById()區別在於:
Activity需要對setContextView()後的Layout才能由findViewById()獲得View。
View隻需要有對象即可由findViewById()獲得在View中包含id的View。
2、在資源獲取方面主要獲取那個apk下的資源主要是由Context決定。
在資源apk沒安裝前:
資源文件安裝後:
主apk包名:com.app.share;
資源apk包名:com.app.share2;
主Activity中獲取資源apk中R,並且生成Layout對id為button1的按鈕設置監聽。
Java代碼
public class StartAct extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Button btn = new Button(this);
btn.setText("TO SECOND");
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(StartAct.this, SecontAct.class);
StartAct.this.startActivity(intent);
}
});
this.setContentView(btn);
try {
Context other = this.createPackageContext("com.app.share2", CONTEXT_IGNORE_SECURITY|CONTEXT_INCLUDE_CODE);
Class<?> c = other.getClassLoader().loadClass("com.app.share2.R");
Class<?>[] cl = c.getClasses();
int b =0;
for (int i = 0; i < cl.length; i++) {
Log.d("TAG", cl[i].getSimpleName());
Field field[] = cl[i].getFields();
for (int j = 0; j < field.length; j++) {
Log.d("TAG", "NAME:"+field[j].getName()+"–VALUE:"+field[j].getInt(field[j].getName()));
if(field[j].getName().equals("button1")) {
b = field[j].getInt(field[j].getName());
Log.d("TAG", "——–id");
}
};
}
View v = LayoutInflater.from(other).inflate(R.layout.main, null);
Button btn1 = (Button) v.findViewById(b);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("TAG", "BUTTON FROM Share2");
Toast.makeText(StartAct.this, "BUTTON FROM Share2", Toast.LENGTH_SHORT).show();
}
});
this.setContentView(v);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
資源apk包Layout
Xml代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Share2"
/>
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
作者“zhujianjia”