我们为什么要学习插件化Activity呢?学习又有什么用呢?
使用方向:
SDK或者library
我们都知道Activity对象是由系统创建产生的,所以我们必须在AndroidManifest.xml文件下引入该Activity,从而实现Activity的创建.
这时我们就要想如何不引入,就能创建Activity的对象呢?
然而他的原理是什么呢?
答:反射
对就是反射,通过一个Activity进行反射创造对象,并将其生命周期方法帮其回调,从而实现不在AndroidManifest.xml文件下引如Activity,就能创建Activity对象啦
好了话不多说开始上货:
//所有Activity都是反射这个Activity
public class ChangChongActivity extends Activity implements Serializable {
private ActivityAdapter mAdapter;
private Activity rootActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(getWindow().FEATURE_NO_TITLE);
this.rootActivity = this;
Intent intent = getIntent();
if(intent!=null){
String activityName = intent.getStringExtra("ActivityName");
if(!TextUtils.isEmpty(activityName)){
try {
mAdapter = (ActivityAdapter) Class.forName(activityName).newInstance();
mAdapter.onCreateAdapter(rootActivity, savedInstanceState);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(mAdapter!=null){
mAdapter.onActivityResultAdapter(requestCode, resultCode, data);
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
if(mAdapter!=null){
mAdapter.onStartAdapter();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(mAdapter!=null){
mAdapter.onKeyDownAdapter(keyCode, event);
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onStop() {
super.onStop();
if(mAdapter!=null){
mAdapter.onActivityStop();
}
}
}
//Activity生命周期回调接口
public interface ActivityAdapter {
void onCreateAdapter(Activity activity,Bundle savedInstanceState);
void onActivityResultAdapter(int requestCode, int resultCode, Intent data);
void onStartAdapter();
void onClickAdapter(View v);
void onDestroyAdapter();
boolean onKeyDownAdapter(int keyCode, KeyEvent event);
void onActivityStop();
}
当你的Class想要是Activity时就继承BaseActivity
public class BaseActivity implements ActivityAdapter{
public Activity rootActivaty;
//onCreate方法
@Override
public void onCreateAdapter(Activity activity, Bundle savedInstanceState) {
// TODO Auto-generated method stub
this.rootActivaty = activity;
}
@Override
public void onActivityResultAdapter(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
}
@Override
public void onStartAdapter() {
// TODO Auto-generated method stub
}
@Override
public void onClickAdapter(View v) {
// TODO Auto-generated method stub
}
@Override
public void onDestroyAdapter() {
// TODO Auto-generated method stub
}
@Override
public boolean onKeyDownAdapter(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onActivityStop() {
}
}